publish.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const ipfsClient = require('ipfs-http-client')
  2. const ipfs = ipfsClient('localhost', '5001', { protocol: 'http' })
  3. const debug = require('debug')('discovery::publish')
  4. const PUBLISH_KEY = 'self' // 'services'
  5. function bufferFrom (data) {
  6. return Buffer.from(JSON.stringify(data), 'utf-8')
  7. }
  8. function encodeServiceInfo (info) {
  9. return bufferFrom({
  10. serialized: JSON.stringify(info)
  11. // signature: ''
  12. })
  13. }
  14. async function publish (service_info) {
  15. const keys = await ipfs.key.list()
  16. let services_key = keys.find((key) => key.name === PUBLISH_KEY)
  17. // generate a new services key if not found
  18. if (PUBLISH_KEY !== 'self' && !services_key) {
  19. debug('generating ipns services key')
  20. services_key = await ipfs.key.gen(PUBLISH_KEY, {
  21. type: 'rsa',
  22. size: 2048
  23. })
  24. }
  25. if (!services_key) {
  26. throw new Error('No IPFS publishing key available!')
  27. }
  28. debug('adding service info file to node')
  29. const files = await ipfs.add(encodeServiceInfo(service_info))
  30. debug('publishing...')
  31. const published = await ipfs.name.publish(files[0].hash, {
  32. key: PUBLISH_KEY,
  33. resolve: false
  34. // lifetime: // string - Time duration of the record. Default: 24h
  35. // ttl: // string - Time duration this record should be cached
  36. })
  37. debug(published)
  38. return services_key.id
  39. }
  40. module.exports = {
  41. publish
  42. }