UNPKG

ember-cli-test-imagine-api

Version:

Create an Imaginary API in CoffeeScript with a declarative interface and neumonic for resources

96 lines (79 loc) 3.21 kB
`import Ember from 'ember'` class Imagine @verbose: true @server: null @api: null @call_history: null @setApi: (api) -> @api = api # private @_ensure_prentender: -> unless @server @call_history = {} @server = sinon.fakeServer.create(); # docs suggest using respondImmediately # but autoRespond works better with ember # plus it acts more like it is network operation # @server.autoRespondAfter = 2 # miliseconds @server.autoRespond = true @callCount: (verb,resource) -> verb = verb.toUpperCase() if @call_history[verb]?[resource]?['count'] @call_history[verb][resource]['count'] else 0 @requestDataHistory: (verb, resource) -> verb = verb.toUpperCase() if @call_history[verb]?[resource]?['requests'] @call_history[verb][resource]['requests'] else [] @lastRequestData: (verb,resource) -> requests = @requestDataHistory(verb,resource) if requests.length > 0 requests[requests.length - 1] else undefined @called: (verb,resource) -> @callCount(verb,resource) > 0 @json: (opts) -> @_ensure_prentender() headers = {"Content-Type": "application/json"} for method, api of opts # do is required when using for loops to avoid closure + variable hoisting bug do (method,api) => for apiKey, response of api do (apiKey, response) => http_verb = method.toUpperCase() if @api[apiKey] response_body = JSON.stringify(response.body) resource_location = @api[apiKey] if @verbose console.log("ImagineApi: Created Mock : method: #{http_verb} #{resource_location} [#{response.status},#{JSON.stringify(headers)},#{response_body}]") @server.respondWith(http_verb, resource_location, (xhr, id) => if @verbose console.log("--- ImagineApi: Responding with : method: #{http_verb} #{resource_location} [#{response.status},#{JSON.stringify(headers)},#{response_body}]") @call_history[http_verb] ||= {} @call_history[http_verb][apiKey] ||= {} @call_history[http_verb][apiKey]['count'] ||= 0 @call_history[http_verb][apiKey]['count']++ @call_history[http_verb][apiKey]['requests'] ||= [] Ember.run => content_type = xhr.requestHeaders["Content-Type"] if content_type?.indexOf("json") > -1 obj = JSON.parse(xhr.requestBody) @call_history[http_verb][apiKey]['requests'].push(obj) else if @verbose console.log("- WARN - ImagineApi.json Request Expected Content-Type JSON not found; Found #{content_type}") @call_history[http_verb][apiKey]['requests'].push(xhr.requestBody) xhr.respond(response.status, headers, response_body) ) else console.log("#{apiKey} is not specified in #{@api}") @stop : -> if @server @server.restore() @server = null `export default Imagine`