index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use strict'
  2. const fetch = require('npm-registry-fetch')
  3. const figgyPudding = require('figgy-pudding')
  4. const getStream = require('get-stream')
  5. const validate = require('aproba')
  6. const HooksConfig = figgyPudding({
  7. package: {},
  8. limit: {},
  9. offset: {},
  10. Promise: {default: () => Promise}
  11. })
  12. const eu = encodeURIComponent
  13. const cmd = module.exports = {}
  14. cmd.add = (name, endpoint, secret, opts) => {
  15. opts = HooksConfig(opts)
  16. validate('SSSO', [name, endpoint, secret, opts])
  17. let type = 'package'
  18. if (name.match(/^@[^/]+$/)) {
  19. type = 'scope'
  20. }
  21. if (name[0] === '~') {
  22. type = 'owner'
  23. name = name.substr(1)
  24. }
  25. return fetch.json('/-/npm/v1/hooks/hook', opts.concat({
  26. method: 'POST',
  27. body: { type, name, endpoint, secret }
  28. }))
  29. }
  30. cmd.rm = (id, opts) => {
  31. opts = HooksConfig(opts)
  32. validate('SO', [id, opts])
  33. return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, opts.concat({
  34. method: 'DELETE'
  35. }, opts)).catch(err => {
  36. if (err.code === 'E404') {
  37. return null
  38. } else {
  39. throw err
  40. }
  41. })
  42. }
  43. cmd.update = (id, endpoint, secret, opts) => {
  44. opts = HooksConfig(opts)
  45. validate('SSSO', [id, endpoint, secret, opts])
  46. return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, opts.concat({
  47. method: 'PUT',
  48. body: {endpoint, secret}
  49. }, opts))
  50. }
  51. cmd.find = (id, opts) => {
  52. opts = HooksConfig(opts)
  53. validate('SO', [id, opts])
  54. return fetch.json(`/-/npm/v1/hooks/hook/${eu(id)}`, opts)
  55. }
  56. cmd.ls = (opts) => {
  57. return getStream.array(cmd.ls.stream(opts))
  58. }
  59. cmd.ls.stream = (opts) => {
  60. opts = HooksConfig(opts)
  61. const {package: pkg, limit, offset} = opts
  62. validate('S|Z', [pkg])
  63. validate('N|Z', [limit])
  64. validate('N|Z', [offset])
  65. return fetch.json.stream('/-/npm/v1/hooks', 'objects.*', opts.concat({
  66. query: {
  67. package: pkg,
  68. limit,
  69. offset
  70. }
  71. }))
  72. }