Skip to content
Snippets Groups Projects
Commit 5a76911b authored by Berend Sliedrecht's avatar Berend Sliedrecht
Browse files

linted and code cleanup for ssi-abstraction


Signed-off-by: default avatarBerend Sliedrecht <blu3beri@proton.me>
parent 9c5d1661
No related branches found
No related tags found
2 merge requests!9feat(ssi): Establish a trusted connection with yourself,!8Project house-keeping, refactoring and reorganizing
Showing
with 91 additions and 90 deletions
import * as Joi from 'joi'; import Joi from 'joi';
const validationSchema = Joi.object({ const validationSchema = Joi.object({
NATS_URL: Joi.string().required(), NATS_URL: Joi.string().required(),
......
/* eslint-disable */
import { subscribe } from './listener'; import { subscribe } from './listener';
describe('listener', () => { describe('listener', () => {
it('should subscribe agent to available events', async () => { it('should subscribe agent to available events', async () => {
const agent = { const agent = {
events: { events: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
on: (eventName: string, cb: () => void) => {}, on: (eventName: string, cb: () => void) => {},
}, },
}; };
......
...@@ -9,12 +9,12 @@ import { listenerConfig } from './listenerConfig'; ...@@ -9,12 +9,12 @@ import { listenerConfig } from './listenerConfig';
* @param agent - the agent that has been initialized on startup * @param agent - the agent that has been initialized on startup
* @param natsClient - the client that specifies how events are published * @param natsClient - the client that specifies how events are published
*/ */
export const subscribe = async ( export const subscribe = (
agent: Agent, agent: Agent,
natsClient: NatsClientService, natsClient: NatsClientService,
) => { ) => {
for (let i = 0; i < listenerConfig.length; i += 1) { for (let i = 0; i < listenerConfig.length; i += 1) {
agent.events.on(listenerConfig[i], async ({ payload }: any) => { agent.events.on(listenerConfig[i], ({ payload }) => {
logger.info( logger.info(
`${listenerConfig[i]} called. Payload: ${JSON.stringify(payload)}`, `${listenerConfig[i]} called. Payload: ${JSON.stringify(payload)}`,
); );
......
...@@ -53,18 +53,16 @@ const agentFactory = { ...@@ -53,18 +53,16 @@ const agentFactory = {
} }
const indyLedgers: LedgerInfo[] = ledgerIds.map((id: LedgerIds) => { const indyLedgers: LedgerInfo[] = ledgerIds.map((id: LedgerIds) => {
const ledgerId: LedgerIds = id; if (!LEDGER_GENESIS?.[id]) {
if (!LEDGER_GENESIS?.[ledgerId]) {
throw new Error( throw new Error(
`No pool transaction genesis provided for ledger ${ledgerId}`, `No pool transaction genesis provided for ledger ${id}`,
); );
} }
const ledger: LedgerInfo = { const ledger: LedgerInfo = {
id: `${ledgerId}_Genesis`, id: `${id}_Genesis`,
indyNamespace: `${ledgerNamespaces[ledgerId]}`, indyNamespace: `${ledgerNamespaces[id]}`,
genesisTransactions: LEDGER_GENESIS?.[ledgerId], genesisTransactions: LEDGER_GENESIS?.[id],
isProduction: false, isProduction: false,
}; };
...@@ -95,7 +93,7 @@ const agentFactory = { ...@@ -95,7 +93,7 @@ const agentFactory = {
agent.registerOutboundTransport(new HttpOutboundTransport()); agent.registerOutboundTransport(new HttpOutboundTransport());
await agent.initialize(); await agent.initialize();
await subscribe(agent, natsClient); subscribe(agent, natsClient);
if (agent.isInitialized) { if (agent.isInitialized) {
ledgerIds.map(async (id: LedgerIds) => { ledgerIds.map(async (id: LedgerIds) => {
...@@ -160,7 +158,7 @@ const agentFactory = { ...@@ -160,7 +158,7 @@ const agentFactory = {
name: NATSServices.SERVICE_NAME, name: NATSServices.SERVICE_NAME,
transport: Transport.NATS, transport: Transport.NATS,
options: { options: {
servers: [config().nats.url as string], servers: [config().nats.url],
}, },
}, },
]), ]),
......
...@@ -28,7 +28,7 @@ import { AgentMid } from './middleware/agentMid.middleware'; ...@@ -28,7 +28,7 @@ import { AgentMid } from './middleware/agentMid.middleware';
], ],
}) })
export class AppModule implements NestModule { export class AppModule implements NestModule {
// eslint-disable-next-line // eslint-disable-next-line class-methods-use-this
configure(consumer: MiddlewareConsumer) { configure(consumer: MiddlewareConsumer) {
consumer.apply(AgentMid).forRoutes('agent', '*/agent'); consumer.apply(AgentMid).forRoutes('agent', '*/agent');
} }
......
...@@ -19,9 +19,11 @@ export class NatsClientService { ...@@ -19,9 +19,11 @@ export class NatsClientService {
logger.info( logger.info(
`Publish nats event: ${NATSServices.SERVICE_NAME}/${eventName}`, `Publish nats event: ${NATSServices.SERVICE_NAME}/${eventName}`,
); );
const event = { const event = {
endpoint: `${NATSServices.SERVICE_NAME}/${eventName}`, endpoint: `${NATSServices.SERVICE_NAME}/${eventName}`,
}; };
this.client.emit(event, data); this.client.emit(event, data);
} }
} }
......
...@@ -44,13 +44,14 @@ export class DidCommController { ...@@ -44,13 +44,14 @@ export class DidCommController {
@All('/:property/:method') @All('/:property/:method')
async generic(@Param() params: GenericParams, @Body() body: GenericBody) { async generic(@Param() params: GenericParams, @Body() body: GenericBody) {
logger.info( logger.info(
`Received request ${params.property}/${params.method}, body: ${body}`, `Received request ${params.property}/${params.method}, body: ${JSON.stringify(body)}`,
); );
const { property, method } = params; const { property, method } = params;
const prop: any = this.agent[property]; const prop: any = this.agent[property];
let response = await prop[method].apply(prop, prepareInputData(body.data)); // eslint-disable-line // eslint-disable-next-line prefer-spread
let response = await prop[method].apply(prop, prepareInputData(body.data));
if (body.subMethod && body.subMethod.name) { if (body.subMethod && body.subMethod.name) {
const path = body.subMethod.name.split('.'); const path = body.subMethod.name.split('.');
......
...@@ -14,7 +14,7 @@ import config from '@config/config'; ...@@ -14,7 +14,7 @@ import config from '@config/config';
name: NATSServices.SERVICE_NAME, name: NATSServices.SERVICE_NAME,
transport: Transport.NATS, transport: Transport.NATS,
options: { options: {
servers: [config().nats.url as string], servers: [config().nats.url],
}, },
}, },
]), ]),
......
...@@ -38,53 +38,53 @@ export interface GenericParams { ...@@ -38,53 +38,53 @@ export interface GenericParams {
// | 'createOutOfBandRequest' // | 'createOutOfBandRequest'
// | 'acceptRequest' // | 'acceptRequest'
| 'declineRequest' | 'declineRequest'
// | 'acceptPresentation' // | 'acceptPresentation'
// | 'getRequestedCredentialsForProofRequest' // | 'getRequestedCredentialsForProofRequest'
// | 'autoSelectCredentialsForProofRequest' // | 'autoSelectCredentialsForProofRequest'
// | 'sendProblemReport' // | 'sendProblemReport'
// | 'sendMessage' // | 'sendMessage'
// | 'findAllByQuery' // | 'findAllByQuery'
// | 'registerPublicDid' // | 'registerPublicDid'
// | 'getPublicDid' // | 'getPublicDid'
// | 'registerSchema' // | 'registerSchema'
// | 'getSchema' // | 'getSchema'
// | 'registerCredentialDefinition' // | 'registerCredentialDefinition'
// | 'getCredentialDefinition' // | 'getCredentialDefinition'
// | 'proposeCredential' // | 'proposeCredential'
// | 'acceptProposal' // | 'acceptProposal'
// | 'negotiateProposal' // | 'negotiateProposal'
// | 'offerCredential' // | 'offerCredential'
// | 'createOutOfBandOffer' // | 'createOutOfBandOffer'
// | 'acceptOffer' // | 'acceptOffer'
// | 'declineOffer' // | 'declineOffer'
// | 'negotiateOffer' // | 'negotiateOffer'
// | 'acceptCredential' // | 'acceptCredential'
// | 'initiateMessagePickup' // | 'initiateMessagePickup'
// | 'pickupMessages' // | 'pickupMessages'
// | 'setDefaultMediator' // | 'setDefaultMediator'
// | 'notifyKeylistUpdate' // | 'notifyKeylistUpdate'
// | 'findDefaultMediatorConnection' // | 'findDefaultMediatorConnection'
// | 'discoverMediation' // | 'discoverMediation'
// | 'requestMediation' // | 'requestMediation'
// | 'findByConnectionId' // | 'findByConnectionId'
// | 'getMediators' // | 'getMediators'
// | 'findDefaultMediator' // | 'findDefaultMediator'
// | 'requestAndAwaitGrant' // | 'requestAndAwaitGrant'
// | 'provision' // | 'provision'
// | 'queueMessage' // | 'queueMessage'
// | 'grantRequestedMediation' // | 'grantRequestedMediation'
// | 'queryFeatures' // | 'queryFeatures'
// | 'initialize' // | 'initialize'
// | 'create' // | 'create'
// | 'open' // | 'open'
// | 'close' // | 'close'
// | 'delete' // | 'delete'
// | 'initPublicDid' // | 'initPublicDid'
// | 'createDid' // | 'createDid'
// | 'pack' // | 'pack'
// | 'unpack' // | 'unpack'
| 'sign' | 'sign'
| 'verify'; | 'verify';
// | 'generateNonce'; // | 'generateNonce';
} }
...@@ -218,9 +218,9 @@ export const checkAll = ( ...@@ -218,9 +218,9 @@ export const checkAll = (
} }
if ( if (
body.subMethod && body.subMethod
body.subMethod.name && && body.subMethod.name
subMethodsList.indexOf(body.subMethod.name) <= -1 && subMethodsList.indexOf(body.subMethod.name) <= -1
) { ) {
success = false; success = false;
messages.push('"subMethod name" either does not exist or is not allowed.'); messages.push('"subMethod name" either does not exist or is not allowed.');
......
...@@ -27,14 +27,15 @@ export class ExceptionHandler implements ExceptionFilter { ...@@ -27,14 +27,15 @@ export class ExceptionHandler implements ExceptionFilter {
const response = ctx.getResponse(); const response = ctx.getResponse();
let statusCode = HttpStatus.INTERNAL_SERVER_ERROR; let statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
let message = let message = exception.message.error || exception.message || 'Something went wrong!';
exception.message.error || exception.message || 'Something went wrong!';
if (exception instanceof HttpException) { if (exception instanceof HttpException) {
const errorResponse: any = exception.getResponse(); const errorResponse = exception.getResponse();
statusCode = exception.getStatus(); statusCode = exception.getStatus();
message = errorResponse.error || message; message = typeof errorResponse === 'object' && 'error' in errorResponse
? errorResponse.error
: errorResponse || message;
} }
const responseBody: ResponseType = { const responseBody: ResponseType = {
......
import { Logger } from 'winston'; import winston, { Logger } from 'winston';
import ecsFormat from '@elastic/ecs-winston-format'; import ecsFormat from '@elastic/ecs-winston-format';
// import { ElasticsearchTransport } from 'winston-elasticsearch';
import winston = require('winston');
// import { ElasticsearchTransport } from 'winston-elasticsearch';
// const esTransportOpts = { // const esTransportOpts = {
// clientOpts: { node: process.env.ECSURL }, // clientOpts: { node: process.env.ECSURL },
// }; // };
...@@ -21,7 +20,8 @@ const logger: Logger = winston.createLogger({ ...@@ -21,7 +20,8 @@ const logger: Logger = winston.createLogger({
], ],
}); });
logger.on('error', (error) => { logger.on('error', (error: Error) => {
// eslint-disable-next-line no-console
console.error('Error in logger caught', error); console.error('Error in logger caught', error);
}); });
......
import { Controller, Get, HttpStatus } from '@nestjs/common'; import { Controller, Get, HttpStatus } from '@nestjs/common';
import { ResponseType } from '@common/response';
@Controller('health') @Controller('health')
export class HealthController { export class HealthController {
...@@ -14,7 +13,7 @@ export class HealthController { ...@@ -14,7 +13,7 @@ export class HealthController {
return { return {
statusCode: HttpStatus.OK, statusCode: HttpStatus.OK,
message: `${new Date()}`, message: `${new Date()}`,
} as ResponseType; };
} }
} }
......
...@@ -18,16 +18,19 @@ async function bootstrap() { ...@@ -18,16 +18,19 @@ async function bootstrap() {
await app.startAllMicroservices(); await app.startAllMicroservices();
const afjPort = configService.get('afjExtPort') || 3001;
const servicePort = configService.get('PORT') || 3000;
const afjExtConfig = { const afjExtConfig = {
port: configService.get('afjExtPort') || 3001, port: afjPort,
}; };
await startServer(agent, afjExtConfig); await startServer(agent, afjExtConfig);
logger.info( logger.info(`Listening AFJ ext on Port: ${afjPort}`);
`Listening AFJ ext on Port:${configService.get('afjExtPort')}` || 3001,
); await app.listen(servicePort, () => {
await app.listen(configService.get('PORT') || 3000, () => { logger.info(`Listening on Port: ${servicePort}`);
logger.info(`Listening on Port:${configService.get('PORT')}` || 3000);
}); });
} }
bootstrap(); bootstrap();
import { Injectable, NestMiddleware, HttpStatus } from '@nestjs/common'; import { Injectable, NestMiddleware, HttpStatus } from '@nestjs/common';
import { Request, NextFunction, Response } from 'express'; import { Request, NextFunction, Response } from 'express';
import { checkAll } from '../didComm/utils/whitelist'; import { checkAll } from '../didComm/utils/whitelist';
import { ResponseType } from '../common/response';
/** /**
* Middleware that checks validity of provided params and body * Middleware that checks validity of provided params and body
...@@ -9,7 +8,7 @@ import { ResponseType } from '../common/response'; ...@@ -9,7 +8,7 @@ import { ResponseType } from '../common/response';
*/ */
@Injectable() @Injectable()
export class AgentMid implements NestMiddleware { export class AgentMid implements NestMiddleware {
// eslint-disable-next-line // eslint-disable-next-line class-methods-use-this
use(req: Request, res: Response, next: NextFunction) { use(req: Request, res: Response, next: NextFunction) {
const [, prop, method] = req.url.split('/'); const [, prop, method] = req.url.split('/');
if (prop === 'info') { if (prop === 'info') {
...@@ -22,7 +21,7 @@ export class AgentMid implements NestMiddleware { ...@@ -22,7 +21,7 @@ export class AgentMid implements NestMiddleware {
res.send({ res.send({
statusCode: HttpStatus.BAD_REQUEST, statusCode: HttpStatus.BAD_REQUEST,
error: whiteListErrors.messages, error: whiteListErrors.messages,
} as ResponseType); });
res.end(); res.end();
return; return;
} }
...@@ -31,7 +30,7 @@ export class AgentMid implements NestMiddleware { ...@@ -31,7 +30,7 @@ export class AgentMid implements NestMiddleware {
res.send({ res.send({
statusCode: HttpStatus.BAD_REQUEST, statusCode: HttpStatus.BAD_REQUEST,
message: 'subMethod.name has to be specified', message: 'subMethod.name has to be specified',
} as ResponseType); });
res.end(); res.end();
return; return;
} }
......
...@@ -18,6 +18,5 @@ describe('HealthController (e2e)', () => { ...@@ -18,6 +18,5 @@ describe('HealthController (e2e)', () => {
await app.close(); await app.close();
}); });
it('/health (GET)', () => it('/health (GET)', () => request(app.getHttpServer()).get('/health').expect(200));
request(app.getHttpServer()).get('/health').expect(200));
}); });
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment