Files
x402-base-facilitator/src/controllers/rest-api/ipfs/controller.js
T

102 lines
2.7 KiB
JavaScript
Raw Normal View History

2023-10-23 20:28:17 -07:00
/*
REST API Controller library for the /ipfs route
*/
import wlogger from '../../../adapters/wlogger.js'
class IpfsRESTControllerLib {
constructor (localConfig = {}) {
// Dependency Injection.
this.adapters = localConfig.adapters
if (!this.adapters) {
throw new Error(
'Instance of Adapters library required when instantiating /ipfs REST Controller.'
)
}
this.useCases = localConfig.useCases
if (!this.useCases) {
throw new Error(
'Instance of Use Cases library required when instantiating /ipfs REST Controller.'
)
}
// Encapsulate dependencies
// this.UserModel = this.adapters.localdb.Users
// this.userUseCases = this.useCases.user
2023-10-28 09:17:48 -07:00
// Bind 'this' object to all subfunctions
this.getStatus = this.getStatus.bind(this)
this.getPeers = this.getPeers.bind(this)
this.getRelays = this.getRelays.bind(this)
this.handleError = this.handleError.bind(this)
2023-10-23 20:28:17 -07:00
}
/**
* @api {get} /ipfs Get status on IPFS infrastructure
* @apiPermission public
* @apiName GetIpfsStatus
* @apiGroup REST BCH
*
* @apiExample Example usage:
* curl -H "Content-Type: application/json" -X GET localhost:5001/ipfs
*
*/
async getStatus (ctx) {
try {
2023-10-28 09:17:48 -07:00
const status = await this.adapters.ipfs.getStatus()
2023-10-23 20:28:17 -07:00
ctx.body = { status }
} catch (err) {
wlogger.error('Error in ipfs/controller.js/getStatus(): ')
// ctx.throw(422, err.message)
2023-10-28 09:17:48 -07:00
this.handleError(ctx, err)
2023-10-23 20:28:17 -07:00
}
}
// Return information on IPFS peers this node is connected to.
async getPeers (ctx) {
try {
const showAll = ctx.request.body.showAll
2023-10-28 09:17:48 -07:00
const peers = await this.adapters.ipfs.getPeers(showAll)
2023-10-23 20:28:17 -07:00
ctx.body = { peers }
} catch (err) {
wlogger.error('Error in ipfs/controller.js/getPeers(): ')
// ctx.throw(422, err.message)
2023-10-28 09:17:48 -07:00
this.handleError(ctx, err)
2023-10-23 20:28:17 -07:00
}
}
// Get data about the known Circuit Relays. Hydrate with data from peers list.
async getRelays (ctx) {
try {
2023-10-28 09:17:48 -07:00
const relays = await this.adapters.ipfs.getRelays()
2023-10-23 20:28:17 -07:00
ctx.body = { relays }
} catch (err) {
wlogger.error('Error in ipfs/controller.js/getRelays(): ')
// ctx.throw(422, err.message)
2023-10-28 09:17:48 -07:00
this.handleError(ctx, err)
2023-10-23 20:28:17 -07:00
}
}
// DRY error handler
handleError (ctx, err) {
// If an HTTP status is specified by the buisiness logic, use that.
if (err.status) {
if (err.message) {
ctx.throw(err.status, err.message)
} else {
ctx.throw(err.status)
}
} else {
// By default use a 422 error if the HTTP status is not specified.
ctx.throw(422, err.message)
}
}
}
// module.exports = IpfsRESTControllerLib
export default IpfsRESTControllerLib