purest.js 1.2 KB

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