purest.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const fs = require('fs')
  2. const qs = require('querystring')
  3. const fixtures = require('../fixtures').providers
  4. function has (object, property) {
  5. return Object.prototype.hasOwnProperty.call(object, property)
  6. }
  7. class MockPurest {
  8. constructor (opts) {
  9. const methodsToMock = ['query', 'select', 'where', 'auth', 'json', 'options']
  10. const httpMethodsToMock = ['get', 'put', 'post', 'head', 'delete']
  11. methodsToMock.forEach((item) => {
  12. this[item] = () => this
  13. })
  14. httpMethodsToMock.forEach((item) => {
  15. this[item] = (url) => {
  16. this._requestUrl = url
  17. this._method = item
  18. return this
  19. }
  20. })
  21. this.opts = opts
  22. }
  23. qs (data) {
  24. this._query = qs.stringify(data)
  25. return this
  26. }
  27. request (done) {
  28. if (typeof done === 'function') {
  29. const responses = fixtures[this.opts.providerName].responses
  30. const url = this._query ? `${this._requestUrl}?${this._query}` : this._requestUrl
  31. const endpointResponses = responses[url] || responses[this._requestUrl]
  32. if (endpointResponses == null || !has(endpointResponses, this._method)) {
  33. done(new Error(`No fixture for ${this._method} ${url}`))
  34. return
  35. }
  36. const body = endpointResponses[this._method]
  37. done(null, { body, statusCode: 200 }, body)
  38. }
  39. return this
  40. }
  41. on (evt, cb) {
  42. if (evt === 'response') {
  43. cb(fs.createReadStream('./README.md'))
  44. }
  45. return this
  46. }
  47. }
  48. module.exports = () => {
  49. return (options) => new MockPurest(options)
  50. }