|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const isEmpty = require('lodash.isempty') |
| 4 | +const { FilebaseClient } = require('@filebase/client') |
| 5 | +const { filesFromPath } = require('files-from-path') |
| 6 | +const { default: axios } = require('axios') |
| 7 | + |
| 8 | +/** |
| 9 | + * @typedef {import('./types').FilebaseOptions} FilebaseOptions |
| 10 | + * @typedef {import('./types').PinDirOptions} PinDirOptions |
| 11 | + */ |
| 12 | + |
| 13 | +const PIN_HASH_URL = 'https://api.filebase.io/v1/ipfs/pins' |
| 14 | + |
| 15 | +class Filebase { |
| 16 | + /** |
| 17 | + * @param {FilebaseOptions} options |
| 18 | + */ |
| 19 | + constructor ({ apiKey, secretApiKey, bucket }) { |
| 20 | + if ([apiKey, secretApiKey, bucket].some(isEmpty)) { |
| 21 | + throw new Error('apiKey and secretApiKey are required for Pinata') |
| 22 | + } |
| 23 | + |
| 24 | + this.auth = { |
| 25 | + api_key: apiKey, |
| 26 | + secret_api_key: secretApiKey, |
| 27 | + bucket: bucket |
| 28 | + } |
| 29 | + |
| 30 | + this.tokenString = btoa(`${this.auth.api_key}:${this.auth.secret_api_key}:${this.auth.bucket}`) |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @param {string} dir |
| 35 | + * @param {PinDirOptions|undefined} options |
| 36 | + * @returns {Promise<string>} |
| 37 | + */ |
| 38 | + async pinDir (dir, { tag, hidden = false } = {}) { |
| 39 | + const files = [] |
| 40 | + for await (const file of filesFromPath(dir, { pathPrefix: dir })) { |
| 41 | + files.push(file) |
| 42 | + } |
| 43 | + |
| 44 | + const cid = await FilebaseClient.storeDirectory( |
| 45 | + { endpoint: 'https://s3.filebase.com', token: this.tokenString }, |
| 46 | + files, |
| 47 | + tag |
| 48 | + ) |
| 49 | + |
| 50 | + return cid |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @param {string} cid |
| 55 | + * @param {string|undefined} tag |
| 56 | + * @returns {Promise<void>} |
| 57 | + */ |
| 58 | + async pinCid (cid, tag) { |
| 59 | + const body = JSON.stringify({ |
| 60 | + cid: cid, |
| 61 | + name: tag |
| 62 | + }) |
| 63 | + |
| 64 | + const config = { |
| 65 | + headers: { |
| 66 | + Authorization: `Bearer ${this.tokenString}`, |
| 67 | + 'Content-Type': 'application/json' |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + await axios.post(PIN_HASH_URL, body, config) |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * @param {string} cid |
| 76 | + * @returns string |
| 77 | + */ |
| 78 | + gatewayUrl (cid) { |
| 79 | + return `https://ipfs.filebase.io/ipfs/${cid}` |
| 80 | + } |
| 81 | + |
| 82 | + static get displayName () { |
| 83 | + return 'Filebase' |
| 84 | + } |
| 85 | + |
| 86 | + get displayName () { |
| 87 | + return Filebase.displayName |
| 88 | + } |
| 89 | + |
| 90 | + static get slug () { |
| 91 | + return 'filebase' |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +module.exports = Filebase |
0 commit comments