Sha256: cf830665f88a4ea1f6c0aa0b1ed22fbe777989a4dfb3e55ffae82d95f4cfe7d6
Contents?: true
Size: 1.33 KB
Versions: 6
Compression:
Stored size: 1.33 KB
Contents
require 'promise' require 'native' require 'json' module Ovto # Wrapper for the fetch API # The server must respond a json text. # # Example: # Ovto.fetch('/api/new_task', 'POST', {title: "do something"}).then{|json_data| # p json_data # }.fail{|e| # Network error, 404 Not Found, JSON parse error, etc. # p e # } def self.fetch(url, method='GET', data=nil) init = `{ method: #{method}, credentials: 'same-origin' // Send cookies to the server (eg. for CookieStore of Rails) }` if method != 'GET' %x{ var headers = {'Content-Type': 'application/json'}; var metaTag = document.querySelector('meta[name=csrf-token]'); if (metaTag) headers['X-CSRF-Token'] = metaTag.content; init['headers'] = headers; init['body'] = #{data.to_json}; } end return _do_fetch(url, init) end # Create an Opal Promise to call fetch API def self._do_fetch(url, init) promise = Promise.new text = error = nil %x{ fetch(url, init).then(response => { if (response.ok) { return response.text(); } else { throw response; } }).then(text => #{promise.resolve(JSON.parse(text))} ).catch(error => #{promise.reject(error)} ); } return promise end end
Version data entries
6 entries across 6 versions & 1 rubygems
Version | Path |
---|---|
ovto-0.7.0 | lib/ovto/fetch.rb |
ovto-0.6.2 | lib/ovto/fetch.rb |
ovto-0.6.1 | lib/ovto/fetch.rb |
ovto-0.6.0 | lib/ovto/fetch.rb |
ovto-0.6.0.rc1 | lib/ovto/fetch.rb |
ovto-0.5.0 | lib/ovto/fetch.rb |