purest.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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']
  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. options (reqOpts) {
  28. this._requestOptions = reqOpts
  29. return this
  30. }
  31. request (done) {
  32. if (typeof done === 'function') {
  33. const responses = fixtures[this.opts.providerName].responses
  34. const url = this._query ? `${this._requestUrl}?${this._query}` : this._requestUrl
  35. const endpointResponses = responses[url] || responses[this._requestUrl]
  36. if (endpointResponses == null || !has(endpointResponses, this._method)) {
  37. done(new Error(`No fixture for ${this._method} ${url}`))
  38. return
  39. }
  40. let statusCode = 200
  41. const validators = fixtures[this.opts.providerName].validators
  42. if (validators && validators[this._requestUrl]) {
  43. statusCode = validators[this._requestUrl](this._requestOptions) ? 200 : 400
  44. }
  45. const body = statusCode === 200 ? endpointResponses[this._method] : {}
  46. done(null, { body, statusCode }, body)
  47. }
  48. return this
  49. }
  50. on (evt, cb) {
  51. if (evt === 'response') {
  52. cb(fs.createReadStream('./README.md'))
  53. }
  54. return this
  55. }
  56. }
  57. module.exports = () => {
  58. return (options) => new MockPurest(options)
  59. }