From f5812fd8c7e49b8ab34800de8bab30cc267295f7 Mon Sep 17 00:00:00 2001 From: ricardo Date: Sun, 27 Mar 2022 12:08:48 -0400 Subject: [PATCH] :shirt: Fix linting issues --- packages/cli/src/PublicApi/helpers.ts | 46 ++++++++----------- packages/cli/src/PublicApi/v1/index.ts | 46 ++++++++----------- .../src/PublicApi/v1/routes/Users/index.ts | 27 ++++++----- packages/cli/src/Server.ts | 14 +++--- packages/cli/src/requests.d.ts | 14 +++++- 5 files changed, 73 insertions(+), 74 deletions(-) diff --git a/packages/cli/src/PublicApi/helpers.ts b/packages/cli/src/PublicApi/helpers.ts index 94f3835b4a..e4b07cd3bc 100644 --- a/packages/cli/src/PublicApi/helpers.ts +++ b/packages/cli/src/PublicApi/helpers.ts @@ -5,49 +5,43 @@ interface IPaginationOffsetDecoded { limit: number; } -export const decodeCursor = (cursor: string) - : IPaginationOffsetDecoded => { - const data = JSON.parse(Buffer.from(cursor, 'base64').toString()); - const unserializedData = querystring.decode(data) as { offset: string, limit: string }; +export const decodeCursor = (cursor: string): IPaginationOffsetDecoded => { + const data = JSON.parse(Buffer.from(cursor, 'base64').toString()) as string; + const unserializedData = querystring.decode(data) as { offset: string; limit: string }; return { offset: parseInt(unserializedData.offset, 10), limit: parseInt(unserializedData.limit, 10), }; }; -export const getNextCursor = (offset: number, limit: number, numberOfRecords: number): string | null => { +export const getNextCursor = ( + offset: number, + limit: number, + numberOfRecords: number, +): string | null => { const retrieveRecordsLength = offset + limit; if (retrieveRecordsLength < numberOfRecords) { - return Buffer.from(JSON.stringify(querystring.encode({ - limit, - offset: offset + limit, - }))).toString('base64'); + return Buffer.from( + JSON.stringify( + querystring.encode({ + limit, + offset: offset + limit, + }), + ), + ).toString('base64'); } return null; }; -export const getSelectableProperties = (table: string) => { +export const getSelectableProperties = (table: 'user' | 'role'): string[] => { return { - user: [ - 'id', - 'email', - 'firstName', - 'lastName', - 'createdAt', - 'updatedAt', - ], - role: [ - 'id', - 'name', - 'scope', - 'createdAt', - 'updatedAt', - ], + user: ['id', 'email', 'firstName', 'lastName', 'createdAt', 'updatedAt'], + role: ['id', 'name', 'scope', 'createdAt', 'updatedAt'], }[table]; }; -export const connectionName = () => { +export const connectionName = (): string => { return 'default'; }; diff --git a/packages/cli/src/PublicApi/v1/index.ts b/packages/cli/src/PublicApi/v1/index.ts index e6b74c8592..d7d338ff61 100644 --- a/packages/cli/src/PublicApi/v1/index.ts +++ b/packages/cli/src/PublicApi/v1/index.ts @@ -1,7 +1,4 @@ - -import { - Application, -} from 'express'; +import { Application, Response } from 'express'; import * as OpenApiValidator from 'express-openapi-validator'; @@ -10,7 +7,8 @@ import path = require('path'); import express = require('express'); import { HttpError, OpenAPIV3 } from 'express-openapi-validator/dist/framework/types'; -import { Db, ResponseHelper } from '../..'; +// eslint-disable-next-line import/no-cycle +import { Db } from '../..'; import config = require('../../../config'); export interface N8nApp { @@ -19,30 +17,32 @@ export interface N8nApp { export const publicApiController = express.Router(); -publicApiController.use(`/v1`, +publicApiController.use( + `/v1`, OpenApiValidator.middleware({ apiSpec: path.join(__dirname, 'openapi.yml'), operationHandlers: path.join(__dirname), - validateRequests: true, // (default) + validateRequests: true, validateApiSpec: true, validateSecurity: { handlers: { + // eslint-disable-next-line @typescript-eslint/naming-convention ApiKeyAuth: async (req, scopes, schema: OpenAPIV3.ApiKeySecurityScheme) => { - const apiKey = req.headers[schema.name.toLowerCase()]; - const user = await Db.collections.User!.find({ + const user = await Db.collections.User?.find({ where: { apiKey, }, relations: ['globalRole'], }); - if (!user.length) { + if (!user?.length) { return false; } if (!config.get('userManagement.isInstanceOwnerSetUp')) { + // eslint-disable-next-line @typescript-eslint/no-throw-literal throw { message: 'asasasas', status: 400, @@ -50,32 +50,26 @@ publicApiController.use(`/v1`, } if (user[0].globalRole.name !== 'owner') { + // eslint-disable-next-line @typescript-eslint/no-throw-literal throw { status: 403, }; } - req.user = user[0]; + [req.user] = user; return true; }, }, }, - })); + }), +); -//add error handler -//@ts-ignore -publicApiController.use((err: HttpError, req, res, next) => { - res.status(err.status || 500).json({ - message: err.message, - errors: err.errors, +// add error handler +// @ts-ignore +publicApiController.use((error: HttpError, req, res: Response) => { + res.status(error.status || 500).json({ + message: error.message, + errors: error.errors, }); - }); - -// export const getRoutes = (): express.Router => { - - - -// return publicApiController; -// }; \ No newline at end of file diff --git a/packages/cli/src/PublicApi/v1/routes/Users/index.ts b/packages/cli/src/PublicApi/v1/routes/Users/index.ts index f1decfd29c..3359eb5e8f 100644 --- a/packages/cli/src/PublicApi/v1/routes/Users/index.ts +++ b/packages/cli/src/PublicApi/v1/routes/Users/index.ts @@ -4,27 +4,30 @@ import { getConnection } from 'typeorm'; import { UserRequest } from '../../../../requests'; import { User } from '../../../../databases/entities/User'; -import { connectionName, decodeCursor, getNextCursor, getSelectableProperties } from '../../../helpers'; - -import * as config from '../../../../../config'; +import { + connectionName, + decodeCursor, + getNextCursor, + getSelectableProperties, +} from '../../../helpers'; export = { - createUsers: async (req: UserRequest.Invite, res: express.Response) => { + createUsers: async (req: UserRequest.Invite, res: express.Response): Promise => { res.json({ success: true }); }, - deleteUser: async (req: UserRequest.Delete, res: express.Response) => { + deleteUser: async (req: UserRequest.Delete, res: express.Response): Promise => { res.json({ success: true }); }, - getUser: async (req: UserRequest.Get, res: express.Response) => { + getUser: async (req: UserRequest.Get, res: express.Response): Promise => { res.json({ success: true }); }, - getUsers: async (req: UserRequest.Get, res: express.Response) => { + getUsers: async (req: UserRequest.Get, res: express.Response): Promise => { let offset = 0; - let limit = parseInt(req.query.limit as string, 10) || 10; + let limit = parseInt(req.query.limit, 10) || 10; const includeRole = req.query?.includeRole?.toLowerCase() === 'true' || false; if (req.query.cursor) { - const cursor = req.query.cursor as string; + const { cursor } = req.query; ({ offset, limit } = decodeCursor(cursor)); } @@ -32,12 +35,12 @@ export = { .getRepository(User) .createQueryBuilder() .leftJoinAndSelect('User.globalRole', 'Role') - .select(getSelectableProperties('user')!.map(property => `User.${property}`)) + .select(getSelectableProperties('user')?.map((property) => `User.${property}`)) .limit(limit) .offset(offset); if (includeRole) { - query.addSelect(getSelectableProperties('role')!.map(property => `Role.${property}`)); + query.addSelect(getSelectableProperties('role')?.map((property) => `Role.${property}`)); } const [users, count] = await query.getManyAndCount(); @@ -47,4 +50,4 @@ export = { nextCursor: getNextCursor(offset, limit, count), }); }, -}; +}; diff --git a/packages/cli/src/Server.ts b/packages/cli/src/Server.ts index 073aff41ec..802be9ed78 100644 --- a/packages/cli/src/Server.ts +++ b/packages/cli/src/Server.ts @@ -564,24 +564,22 @@ class App { // Public API // ---------------------------------------- - - //test routes to create/regenerate/delete token - //NOTE: Only works with admin role - //This should be within the user's management user scope + // test routes to create/regenerate/delete token + // NOTE: Only works with admin role + // This should be within the user's management user scope this.app.post('/token', async (req: express.Request, res: express.Response) => { const ramdonToken = randomBytes(20).toString('hex'); - //@ts-ignore + // @ts-ignore await Db.collections.User!.update({ globalRole: 1 }, { apiKey: ramdonToken }); return ResponseHelper.sendSuccessResponse(res, { token: ramdonToken }, true, 200); }); this.app.delete('/token', async (req: express.Request, res: express.Response) => { - //@ts-ignore + // @ts-ignore await Db.collections.User!.update({ globalRole: 1 }, { apiKey: null }); return ResponseHelper.sendSuccessResponse(res, {}, true, 204); }); - this.app.use(`/${this.publicApiEndpoint}/`, publicApiController); // Parse cookies for easier access @@ -3111,7 +3109,7 @@ async function getExecutionsCount( try { // Get an estimate of rows count. const estimateRowsNumberSql = - 'SELECT n_live_tup FROM pg_stat_all_tables WHERE relname = \'execution_entity\';'; + "SELECT n_live_tup FROM pg_stat_all_tables WHERE relname = 'execution_entity';"; const rows: Array<{ n_live_tup: string }> = await Db.collections.Execution!.query( estimateRowsNumberSql, ); diff --git a/packages/cli/src/requests.d.ts b/packages/cli/src/requests.d.ts index 8fd44309b1..9b997f3eb7 100644 --- a/packages/cli/src/requests.d.ts +++ b/packages/cli/src/requests.d.ts @@ -196,9 +196,19 @@ export declare namespace UserRequest { { inviterId?: string; inviteeId?: string } >; - export type Delete = AuthenticatedRequest<{ id: string, email: string }, {}, {}, { transferId?: string }>; + export type Delete = AuthenticatedRequest< + { id: string; email: string }, + {}, + {}, + { transferId?: string } + >; - export type Get = AuthenticatedRequest<{ id: string, email: string }, {}, {}, { limit: string, cursor: string, includeRole: string }>; + export type Get = AuthenticatedRequest< + { id: string; email: string }, + {}, + {}, + { limit: string; cursor: string; includeRole: string } + >; export type Reinvite = AuthenticatedRequest<{ id: string }>;