Skip to content

Commit

Permalink
Lint fixes and code refactoring changes
Browse files Browse the repository at this point in the history
  • Loading branch information
praveenkumarct committed Jan 31, 2024
1 parent 7727e2b commit 2b3b9ee
Show file tree
Hide file tree
Showing 18 changed files with 84 additions and 157 deletions.
7 changes: 7 additions & 0 deletions processor/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 5 additions & 7 deletions processor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
"name": "payment-integration-template",
"version": "0.0.1",
"description": "Payment provider integration template",
"main": "dist/server/server.js",
"main": "dist/server.js",
"scripts": {
"start": "node dist/server/main.js",
"start:dev": "node_modules/.bin/nodemon -q dist/server/main.js",
"start": "node dist/main.js",
"start:dev": "node_modules/.bin/nodemon -q dist/main.js",
"lint": "prettier --check \"src/**/*.{ts,js,json}\" && eslint --ext .ts src",
"lint:fix": "prettier --write \"src/**/*.{ts,js,json}\" && eslint --fix --ext .ts src",
"build": "tsc -p tsconfig.server.json",
"dev": "ts-node --project tsconfig.server.json src/server/main.ts | pino-pretty",
"dev": "ts-node --project tsconfig.server.json src/main.ts",
"test": "jest --detectOpenHandles",
"connector:post-deploy": "node src/connectors/post-deploy.ts",
"connector:pre-undeploy": "node src/connectors/pre-undeploy.ts"
Expand All @@ -32,15 +32,14 @@
"dotenv": "16.3.1",
"fastify": "4.25.1",
"fastify-plugin": "4.5.1",
"pino": "8.16.2",
"pino-std-serializers": "6.2.2",
"uuid": "^9.0.1"
},
"devDependencies": {
"@jest/globals": "29.7.0",
"@types/jest": "29.5.6",
"@types/node": "20.6.3",
"@types/systemjs": "6.13.4",
"@types/uuid": "^9.0.8",
"@typescript-eslint/eslint-plugin": "6.8.0",
"@typescript-eslint/parser": "6.8.0",
"eslint": "8.51.0",
Expand All @@ -54,7 +53,6 @@
"msw": "1.3.2",
"node-fetch": "3.3.2",
"nodemon": "3.0.1",
"pino-pretty": "10.2.0",
"prettier": "3.0.3",
"systemjs": "6.14.2",
"ts-jest": "29.1.1",
Expand Down
40 changes: 19 additions & 21 deletions processor/src/clients/mockPaymentAPI.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
import { v4 as uuid } from 'uuid';
import {CreatePaymentRequest, MockPaymentProviderResponse} from '../services/types/payment.type';
import {PaymentOutcome} from "../dtos/payment.dto";
import { CreatePaymentRequest, MockPaymentProviderResponse } from '../services/types/payment.type';
import { PaymentOutcome } from '../dtos/payment.dto';

// TODO: Make it class , add interface and provide implementation
export const paymentProviderApi = (): any => {

const allowedCreditCards = ['4111111111111111', '5555555555554444', '341925950237632'];
/**
* @param request
* @returns
*/
const processPayment = async (request: CreatePaymentRequest): Promise<MockPaymentProviderResponse> => {
const paymentMethod = request.data.paymentMethod;
const isAuthorized = isCreditCardAllowed(paymentMethod.cardNumber);

return {
resultCode: isAuthorized ? PaymentOutcome.AUTHORIZED: PaymentOutcome.REJECTED,
pspReference: uuid(),
paymentMethodType: paymentMethod.type,
}
};

const isCreditCardAllowed = (cardNumber: string) => allowedCreditCards.includes(cardNumber);
const allowedCreditCards = ['4111111111111111', '5555555555554444', '341925950237632'];
/**
* @param request
* @returns
*/
const processPayment = async (request: CreatePaymentRequest): Promise<MockPaymentProviderResponse> => {
const paymentMethod = request.data.paymentMethod;
const isAuthorized = isCreditCardAllowed(paymentMethod.cardNumber);

return {
processPayment
resultCode: isAuthorized ? PaymentOutcome.AUTHORIZED : PaymentOutcome.REJECTED,
pspReference: uuid(),
paymentMethodType: paymentMethod.type,
};
};

const isCreditCardAllowed = (cardNumber: string) => allowedCreditCards.includes(cardNumber);

return {
processPayment,
};
};
12 changes: 6 additions & 6 deletions processor/src/connectors/post-deploy.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@

async function postDeploy(properties) {

async function postDeploy(properties: any) {
// TODO: Implement postDeploy scripts if any
}

async function run() {
async function runPostDeployScripts() {
try {
const properties = new Map(Object.entries(process.env));
await postDeploy(properties);
} catch (error) {
process.stderr.write(`Post-deploy failed: ${error.message}\n`);
if (error instanceof Error) {
process.stderr.write(`Post-deploy failed: ${error.message}\n`);
}
process.exitCode = 1;
}
}

run();
runPostDeployScripts();
6 changes: 3 additions & 3 deletions processor/src/connectors/pre-undeploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ async function run() {
try {
await preUndeploy();
} catch (error) {
process.stderr.write(`Post-undeploy failed: ${error.message}\n`);
if (error instanceof Error) {
process.stderr.write(`Post-undeploy failed: ${error.message}\n`);
}
process.exitCode = 1;
}
}

run();
5 changes: 2 additions & 3 deletions processor/src/dtos/payment.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Static, Type} from '@sinclair/typebox';
import { Static, Type } from '@sinclair/typebox';

export const CardPaymentMethod = Type.Object({
// TODO: Remove the fields according to the payment provider solution,
Expand All @@ -8,7 +8,7 @@ export const CardPaymentMethod = Type.Object({
expiryMonth: Type.Number(),
expiryYear: Type.Number(),
cvc: Type.Number(),
holderName: Type.Optional(Type.String())
holderName: Type.Optional(Type.String()),
});

export const PaymentRequestSchema = Type.Object({
Expand All @@ -30,4 +30,3 @@ export const PaymentResponseSchema = Type.Object({

export type PaymentRequestSchemaDTO = Static<typeof PaymentRequestSchema>;
export type PaymentResponseSchemaDTO = Static<typeof PaymentResponseSchema>;

1 change: 0 additions & 1 deletion processor/src/libs/fastify/context/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ export const updateSessionContext = (ctx: Partial<SessionContextData>) => {
});
};


export const requestContextPlugin = fp(async (fastify: FastifyInstance) => {
// Enance the request object with a correlationId property
fastify.decorateRequest('correlationId', '');
Expand Down
15 changes: 5 additions & 10 deletions processor/src/libs/fastify/error-handler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type FastifyReply, type FastifyRequest } from 'fastify';

import { ErrorInvalidField, ErrorRequiredField, Errorx, MultiErrorx } from '@commercetools/connect-payments-sdk';
import { log } from '../logger/pino';
import { log } from '../logger';

const getKeys = (path: string) => path.replace(/^\//, '').split('/');

Expand All @@ -18,12 +18,12 @@ type ValidationObject = {
validation: object;
};

type TError= {
type TError = {
statusCode: number;
code: string;
message: string;
errors?: object[];
}
};

export const errorHandler = (error: Error, req: FastifyRequest, reply: FastifyReply) => {
if (error instanceof Object && (error as unknown as ValidationObject).validation) {
Expand Down Expand Up @@ -56,7 +56,7 @@ export const errorHandler = (error: Error, req: FastifyRequest, reply: FastifyRe
if (error instanceof Errorx) {
return handleErrorx(error, reply);
} else {
log.error({ err: error }, error.message);
log.error(error.message);
return reply.code(500).send({
code: 'General',
message: 'Internal server error.',
Expand All @@ -66,12 +66,7 @@ export const errorHandler = (error: Error, req: FastifyRequest, reply: FastifyRe
};

const handleErrorx = (error: Errorx, reply: FastifyReply) => {
const { cause, ...errorWithoutCause } = error;
if (error.skipLog) {
log.debug({ err: errorWithoutCause, cause }, error.message);
} else {
log.error({ err: errorWithoutCause, cause }, error.message);
}
log.error(error.message);
const errorBuilder: TError = {
statusCode: error.httpErrorStatus,
code: error.code,
Expand Down
26 changes: 13 additions & 13 deletions processor/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import * as dotenv from 'dotenv';
dotenv.config();

import { setupFastify } from "./server";
import { setupFastify } from './server';

(async () => {
const server = await setupFastify();
const server = await setupFastify();

const HOST = '0.0.0.0';
try {
await server.listen({
port: 8080,
host: HOST,
});
} catch (err) {
server.log.error(err);
process.exit(1);
}
})();
const HOST = '0.0.0.0';
try {
await server.listen({
port: 8080,
host: HOST,
});
} catch (err) {
server.log.error(err);
process.exit(1);
}
})();
10 changes: 4 additions & 6 deletions processor/src/payment-sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,22 @@ import {
updateRequestContext,
updateSessionContext,
} from './libs/fastify/context/context';
import { log } from './libs/logger';

export class AppLogger implements Logger {
public debug = (obj: object, message: string) => {
log.debug(obj, message);
// log.debug(obj, message);
};
public info = (obj: object, message: string) => {
log.info(obj, message);
// log.info(obj, message);
};
public warn = (obj: object, message: string) => {
log.warn(obj, message);
// log.warn(obj, message);
};
public error = (obj: object, message: string) => {
log.error(obj, message);
// log.error(obj, message);
};
}


const appLogger = new AppLogger();

export const paymentSDK = setupPaymentSDK({
Expand Down
10 changes: 5 additions & 5 deletions processor/src/routes/config.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ export const configRoutes = async (fastify: FastifyInstance, options: FastifyPlu
const handler = configHandler({
configuration: () => ({
clientKey: config.mockClientKey,
environment: config.mockEnvironment
})
})
environment: config.mockEnvironment,
}),
});

fastify.get('/config', async(request, reply) => {
const result = await handler()
fastify.get('/config', async (request, reply) => {
const result = await handler();
reply.code(result.status).send(result.body);
});
};
5 changes: 2 additions & 3 deletions processor/src/routes/payment.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ import {
PaymentRequestSchema,
PaymentRequestSchemaDTO,
PaymentResponseSchema,
PaymentResponseSchemaDTO
} from "../dtos/payment.dto";
PaymentResponseSchemaDTO,
} from '../dtos/payment.dto';

type PaymentRoutesOptions = {
paymentService: PaymentService;
sessionAuthHook: onRequestHookHandler;
};

export const paymentRoutes = async (fastify: FastifyInstance, opts: FastifyPluginOptions & PaymentRoutesOptions) => {

fastify.post<{ Body: PaymentRequestSchemaDTO; Reply: PaymentResponseSchemaDTO }>(
'/payments',
{
Expand Down
4 changes: 2 additions & 2 deletions processor/src/routes/status.route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {healthCheckCoCoPermissions,statusHandler } from '@commercetools/connect-payments-sdk'
import { healthCheckCoCoPermissions, statusHandler } from '@commercetools/connect-payments-sdk';
import { FastifyInstance, FastifyPluginOptions } from 'fastify';
import { config } from '../config/config';
import { paymentSDK } from '../payment-sdk';
const packageJSON = require('../../../package.json');
const packageJSON = require('../../package.json');

export const statusRoutes = async (fastify: FastifyInstance, opts: FastifyPluginOptions) => {
fastify.get('/ping', async (request, reply) => {
Expand Down
10 changes: 3 additions & 7 deletions processor/src/services/payment.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { CommercetoolsCartService, CommercetoolsPaymentService } from '@commercetools/connect-payments-sdk';
import { paymentProviderApi } from '../clients/mockPaymentAPI';
import {
CreatePayment,
PaymentService,
PaymentServiceOptions
} from './types/payment.type';
import { CreatePayment, PaymentService, PaymentServiceOptions } from './types/payment.type';
import { getSessionContext } from '../libs/fastify/context/context';
import { PaymentOutcome, PaymentResponseSchemaDTO } from '../dtos/payment.dto';

Expand All @@ -18,12 +14,12 @@ export class DefaultPaymentService implements PaymentService {
}

public async createPayment(opts: CreatePayment): Promise<PaymentResponseSchemaDTO> {
let ctCart, ctPayment;
let ctCart;
ctCart = await this.ctCartService.getCart({
id: getSessionContext().cartId,
});

ctPayment = await this.ctPaymentService.createPayment({
const ctPayment = await this.ctPaymentService.createPayment({
amountPlanned: this.ctCartService.getPaymentAmount({
cart: ctCart,
}),
Expand Down
12 changes: 4 additions & 8 deletions processor/src/services/types/payment.type.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { Cart, Payment } from '@commercetools/platform-sdk';
import { CommercetoolsCartService, CommercetoolsPaymentService } from '@commercetools/connect-payments-sdk';
import {
PaymentOutcome,
PaymentRequestSchemaDTO,
PaymentResponseSchemaDTO
} from '../../dtos/payment.dto';
import { PaymentOutcome, PaymentRequestSchemaDTO, PaymentResponseSchemaDTO } from '../../dtos/payment.dto';

export type CreatePayment = {
data: PaymentRequestSchemaDTO;
Expand All @@ -17,9 +13,9 @@ export type CreatePaymentRequest = {
};

export type MockPaymentProviderResponse = {
resultCode: PaymentOutcome,
pspReference: string,
paymentMethodType: string,
resultCode: PaymentOutcome;
pspReference: string;
paymentMethodType: string;
};

export interface PaymentService {
Expand Down
Loading

0 comments on commit 2b3b9ee

Please sign in to comment.