fix(ipfs-service-provider): Synced with upstream

This commit is contained in:
Chris Troutner
2021-07-31 15:55:47 -07:00
7 changed files with 160 additions and 97 deletions
+4 -3
View File
@@ -55,9 +55,10 @@ async function startServer () {
app.use(passport.initialize()) app.use(passport.initialize())
app.use(passport.session()) app.use(passport.session())
// Attach REST API and JSON RPC controllers to the app. // Attach REST API and JSON RPC controllersCt unstable to the app.
const controllers = require('../src/controllers') const Controllers = require('../src/controllers')
await controllers.attachControllers(app) const controllers = new Controllers()
controllers.attachControllers(app)
// Enable CORS for testing // Enable CORS for testing
// THIS IS A SECURITY RISK. COMMENT OUT FOR PRODUCTION // THIS IS A SECURITY RISK. COMMENT OUT FOR PRODUCTION
+78 -37
View File
@@ -11,52 +11,93 @@ require('winston-daily-rotate-file')
const config = require('../../config') const config = require('../../config')
// Configure daily-rotation transport. class Wlogger {
const transport = new winston.transports.DailyRotateFile({ constructor (localConfig = {}) {
filename: `${__dirname.toString()}/../../logs/koa-${config.env}-%DATE%.log`, this.config = config
datePattern: 'YYYY-MM-DD',
zippedArchive: false,
maxSize: '1m', // 1 megabyte
maxFiles: '5d', // 5 days
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
)
})
transport.on('rotate', notifyRotation) // Configure daily-rotation transport.
this.transport = new winston.transports.DailyRotateFile({
filename: `${__dirname.toString()}/../../logs/koa-${
this.config.env
}-%DATE%.log`,
datePattern: 'YYYY-MM-DD',
zippedArchive: false,
maxSize: '1m', // 1 megabyte
maxFiles: '5d', // 5 days
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
)
})
function notifyRotation (oldFilename, newFilename) { this.transport.on('rotate', this.notifyRotation)
wlogger.info('Rotating log files')
// This controls what goes into the log FILES
this.wlogger = winston.createLogger({
level: 'verbose',
format: winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
// new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
// new winston.transports.File({ filename: 'logs/combined.log' })
this.transport
]
})
}
notifyRotation (oldFilename, newFilename) {
this.wlogger.info('Rotating log files')
}
outputToConsole () {
this.wlogger.add(
new winston.transports.Console({
format: winston.format.simple(),
level: 'info'
})
)
}
} }
// transport.on('rotate', notifyRotation)
// function notifyRotation (oldFilename, newFilename) {
// wlogger.info('Rotating log files')
// }
// This controls what goes into the log FILES // This controls what goes into the log FILES
const wlogger = winston.createLogger({ // const wlogger = winston.createLogger({
level: 'verbose', // level: 'verbose',
format: winston.format.json(), // format: winston.format.json(),
transports: [ // transports: [
// // //
// - Write to all logs with level `info` and below to `combined.log` // // - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`. // // - Write all logs error (and below) to `error.log`.
// // //
// new winston.transports.File({ filename: 'logs/error.log', level: 'error' }), // // new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
// new winston.transports.File({ filename: 'logs/combined.log' }) // // new winston.transports.File({ filename: 'logs/combined.log' })
transport // transport
] // ]
}) // })
function outputToConsole () { // function outputToConsole () {
wlogger.add( // wlogger.add(
new winston.transports.Console({ // new winston.transports.Console({
format: winston.format.simple(), // format: winston.format.simple(),
level: 'info' // level: 'info'
}) // })
) // )
} // }
// This controls the logs to CONSOLE // This controls the logs to CONSOLE
// if (config.env !== 'test') { // if (config.env !== 'test') {
// outputToConsole() // outputToConsole()
// } // }
module.exports = { wlogger, notifyRotation, outputToConsole } const logger = new Wlogger()
const wlogger = logger.wlogger
module.exports = { wlogger, Wlogger }
+37 -30
View File
@@ -14,15 +14,18 @@ const JSONRPC = require('./json-rpc')
// Load the Clean Architecture Use Case libraries. // Load the Clean Architecture Use Case libraries.
const UseCases = require('../use-cases') const UseCases = require('../use-cases')
const useCases = new UseCases({ adapters }) // const useCases = new UseCases({ adapters })
// Load the REST API Controllers. // Load the REST API Controllers.
const RESTControllers = require('./rest-api') const RESTControllers = require('./rest-api')
// Top-level function for this library. class Controllers {
// Start the various Controllers and attach them to the app. constructor (localConfig = {}) {
async function attachControllers (app) { this.adapters = adapters
try { this.useCases = new UseCases({ adapters })
}
async attachControllers (app) {
// Get a JWT token and instantiate bch-js with it. Then pass that instance // Get a JWT token and instantiate bch-js with it. Then pass that instance
// to all the rest of the apps controllers and adapters. // to all the rest of the apps controllers and adapters.
await adapters.fullStackJwt.getJWT() await adapters.fullStackJwt.getJWT()
@@ -30,34 +33,38 @@ async function attachControllers (app) {
adapters.bchjs = await adapters.fullStackJwt.instanceBchjs() adapters.bchjs = await adapters.fullStackJwt.instanceBchjs()
// Attach the REST controllers to the Koa app. // Attach the REST controllers to the Koa app.
attachRESTControllers(app) this.attachRESTControllers(app)
// Start IPFS. // Start IPFS.
await adapters.ipfs.start({ bchjs: adapters.bchjs }) await this.adapters.ipfs.start({ bchjs: adapters.bchjs })
attachRPCControllers() this.attachRPCControllers()
} catch (err) { }
console.error('Error in attachControllers()')
throw err // Top-level function for this library.
// Start the various Controllers and attach them to the app.
attachRESTControllers (app) {
const rESTControllers = new RESTControllers({
adapters: this.adapters,
useCases: this.useCases
})
// Attach the REST API Controllers associated with the boilerplate code to the Koa app.
rESTControllers.attachRESTControllers(app)
}
// Add the JSON RPC router to the ipfs-coord adapter.
attachRPCControllers () {
const jsonRpcController = new JSONRPC({
adapters: this.adapters,
useCases: this.useCases
})
// Attach the input of the JSON RPC router to the output of ipfs-coord.
this.adapters.ipfs.ipfsCoordAdapter.attachRPCRouter(
jsonRpcController.router
)
} }
} }
function attachRESTControllers (app) { module.exports = Controllers
const rESTControllers = new RESTControllers({
adapters,
useCases
})
// Attach the REST API Controllers associated with the boilerplate code to the Koa app.
rESTControllers.attachRESTControllers(app)
}
// Add the JSON RPC router to the ipfs-coord adapter.
function attachRPCControllers () {
const jsonRpcController = new JSONRPC({ adapters, useCases })
// Attach the input of the JSON RPC router to the output of ipfs-coord.
adapters.ipfs.ipfsCoordAdapter.attachRPCRouter(jsonRpcController.router)
}
module.exports = { attachControllers }
+4 -11
View File
@@ -3,7 +3,7 @@
functions are called by the /user REST API endpoints. functions are called by the /user REST API endpoints.
*/ */
// const UserModel = require('../adapters/localdb/models/users') const UserEntity = require('../entities/user')
const { wlogger } = require('../adapters/wlogger') const { wlogger } = require('../adapters/wlogger')
class UserLib { class UserLib {
@@ -17,6 +17,7 @@ class UserLib {
} }
// Encapsulate dependencies // Encapsulate dependencies
this.UserEntity = new UserEntity()
this.UserModel = this.adapters.localdb.Users this.UserModel = this.adapters.localdb.Users
} }
@@ -24,17 +25,9 @@ class UserLib {
async createUser (userObj) { async createUser (userObj) {
try { try {
// Input Validation // Input Validation
if (!userObj.email || typeof userObj.email !== 'string') {
throw new Error("Property 'email' must be a string!")
}
if (!userObj.password || typeof userObj.password !== 'string') {
throw new Error("Property 'password' must be a string!")
}
if (!userObj.name || typeof userObj.name !== 'string') {
throw new Error("Property 'name' must be a string!")
}
const user = new this.UserModel(userObj) const userEntity = this.UserEntity.validate(userObj)
const user = new this.UserModel(userEntity)
// Enforce default value of 'user' // Enforce default value of 'user'
user.type = 'user' user.type = 'user'
+20 -10
View File
@@ -1,30 +1,40 @@
// const assert = require('chai').assert const assert = require('chai').assert
const { const { Wlogger } = require('../../../src/adapters/wlogger')
notifyRotation,
outputToConsole
} = require('../../../src/adapters/wlogger')
const sinon = require('sinon') const sinon = require('sinon')
// let uut let uut
let sandbox let sandbox
describe('#wlogger.js', () => { describe('#wlogger', () => {
beforeEach(() => { beforeEach(() => {
sandbox = sinon.createSandbox() sandbox = sinon.createSandbox()
}) })
afterEach(() => sandbox.restore()) afterEach(() => {
sandbox.restore()
uut = new Wlogger()
})
describe('#constructor', () => {
it('should create a new wlogger instance', () => {
uut = new Wlogger()
// console.log('uut: ', uut)
assert.property(uut, 'transport')
})
})
describe('#notifyRotation', () => { describe('#notifyRotation', () => {
it('should notify of a log rotation', () => { it('should notify of a log rotation', () => {
notifyRotation() uut.notifyRotation()
}) })
}) })
describe('#envronment', () => { describe('#envronment', () => {
it('should write to console in non-test environment', () => { it('should write to console in non-test environment', () => {
outputToConsole() uut.outputToConsole()
}) })
}) })
}) })
+16 -5
View File
@@ -7,14 +7,17 @@ const assert = require('chai').assert
const sinon = require('sinon') const sinon = require('sinon')
const adapters = require('../../../src/adapters') const adapters = require('../../../src/adapters')
const { attachControllers } = require('../../../src/controllers') // const { attachControllers } = require('../../../src/controllers')
const Controllers = require('../../../src/controllers')
describe('#Controllers', () => { describe('#Controllers', () => {
// let uut let uut
let sandbox let sandbox
beforeEach(() => { beforeEach(() => {
sandbox = sinon.createSandbox() sandbox = sinon.createSandbox()
uut = new Controllers()
}) })
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
@@ -22,9 +25,9 @@ describe('#Controllers', () => {
describe('#attachControllers', () => { describe('#attachControllers', () => {
it('should attach the controllers', async () => { it('should attach the controllers', async () => {
// mock IPFS // mock IPFS
sandbox.stub(adapters.ipfs, 'start').resolves({})
sandbox.stub(adapters.fullStackJwt, 'getJWT').resolves({}) sandbox.stub(adapters.fullStackJwt, 'getJWT').resolves({})
sandbox.stub(adapters.fullStackJwt, 'instanceBchjs').resolves({}) sandbox.stub(adapters.fullStackJwt, 'instanceBchjs').resolves({})
sandbox.stub(adapters.ipfs, 'start').resolves({})
adapters.ipfs.ipfsCoordAdapter = { adapters.ipfs.ipfsCoordAdapter = {
attachRPCRouter: () => {} attachRPCRouter: () => {}
} }
@@ -33,7 +36,9 @@ describe('#Controllers', () => {
use: () => {} use: () => {}
} }
await attachControllers(app) await uut.attachControllers(app)
assert.isOk(true, 'Not throwing an error is a success')
}) })
it('should catch and throw errors', async () => { it('should catch and throw errors', async () => {
@@ -43,7 +48,13 @@ describe('#Controllers', () => {
.stub(adapters.fullStackJwt, 'getJWT') .stub(adapters.fullStackJwt, 'getJWT')
.rejects(new Error('test error')) .rejects(new Error('test error'))
await attachControllers() const app = {
use: () => {}
}
await uut.attachControllers(app)
assert.fail('Unexpected code path')
} catch (err) { } catch (err) {
// console.log('err.message: ', err.message) // console.log('err.message: ', err.message)
assert.include(err.message, 'test error') assert.include(err.message, 'test error')
+1 -1
View File
@@ -57,7 +57,7 @@ describe('#users-use-case', () => {
} catch (err) { } catch (err) {
// console.log(err) // console.log(err)
// assert.equal(err.status, 422) // assert.equal(err.status, 422)
assert.include(err.message, 'Cannot read property') assert.include(err.message, "Property 'email' must be a string!")
} }
}) })