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