Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: update line length to 120 (VF-3310) #86

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ insert_final_newline = false

[*.js]
trim_trailing_whitespace = false
max_line_length = 150
max_line_length = 120
10 changes: 10 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ module.exports = {
files: ['config/**/*', 'test/**/*'],
extends: ['@voiceflow/eslint-config/utility', '@voiceflow/eslint-config/mocha'],
rules: {
'max-len': [
'error',
{
code: 120,
ignoreUrls: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true,
},
],
// off
'no-unused-expressions': 'off',
},
Expand Down
4 changes: 4 additions & 0 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
...require("@voiceflow/prettier-config"),
printWidth: 120,
};
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@
"ioredis": "^4.28.5",
"jszip": "^3.7.1"
},
"prettier": "@voiceflow/prettier-config",
"repository": {
"type": "git",
"url": "git+https://github.com/voiceflow/backend-utils.git"
Expand Down
6 changes: 5 additions & 1 deletion src/common/zip/reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ export class ZipReader {
});
}

private async *getFilesRecursively(zip: JSZip, config: ZipGetFilesOptions, currentDepth = 0): AsyncGenerator<ZipEntry> {
private async *getFilesRecursively(
zip: JSZip,
config: ZipGetFilesOptions,
currentDepth = 0
): AsyncGenerator<ZipEntry> {
const objects = zip.filter((_, file) => minimatch(file.name, config.path));

let fileCount = 0;
Expand Down
22 changes: 17 additions & 5 deletions src/fixtureGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,16 @@ const createFixture = <T extends ServiceManager<any, any>>(serviceManager: T): T
middlewares: _.mapValues(middlewares, (service) =>
_.mapValues(service, (method) => {
if (method.callback) {
const callbackStub: sinon.SinonStubStatic & { callback?: boolean } = sinon.stub().returns(sinon.stub().callsArg(2));
const callbackStub: sinon.SinonStubStatic & { callback?: boolean } = sinon
.stub()
.returns(sinon.stub().callsArg(2));
callbackStub.callback = true;
return callbackStub;
}

const methodStub: sinon.SinonStubStatic & { validations?: Record<string, sinon.SinonStubStatic> } = sinon.stub().callsArg(2);
const methodStub: sinon.SinonStubStatic & {
validations?: Record<string, sinon.SinonStubStatic>;
} = sinon.stub().callsArg(2);
methodStub.validations = _.mapValues(method.validations, () => sinon.stub().callsArg(2));

return [...Object.values(methodStub.validations), methodStub];
Expand All @@ -56,7 +60,10 @@ const createFixture = <T extends ServiceManager<any, any>>(serviceManager: T): T
} as unknown) as T;
};

const checkFixture = <T extends ServiceManager<any, any>>(fixture: T, expected: FixtureExpect<T['controllers'], T['middlewares']>): void => {
const checkFixture = <T extends ServiceManager<any, any>>(
fixture: T,
expected: FixtureExpect<T['controllers'], T['middlewares']>
): void => {
const { middlewares, controllers } = fixture;

const validations = {
Expand All @@ -78,7 +85,10 @@ const checkFixture = <T extends ServiceManager<any, any>>(fixture: T, expected:
validations.controllers[controller] = {};
}

validations.controllers[controller][method] = _.mapValues(controllerMethod.validations, (stub) => stub.callCount);
validations.controllers[controller][method] = _.mapValues(
controllerMethod.validations,
(stub) => stub.callCount
);
}

controllers[controller][method] = controllerMethod.callCount;
Expand All @@ -97,7 +107,9 @@ const checkFixture = <T extends ServiceManager<any, any>>(fixture: T, expected:
Object.keys(middlewares[service]).forEach((method) => {
const expressMiddlewares = middlewares[service][method];
// if no length -> callback middleware -> it's not an array
const middlewareMethod = expressMiddlewares.length ? expressMiddlewares[expressMiddlewares.length - 1] : expressMiddlewares;
const middlewareMethod = expressMiddlewares.length
? expressMiddlewares[expressMiddlewares.length - 1]
: expressMiddlewares;

if (middlewareMethod.validations) {
if (!validations.middlewares[service]) {
Expand Down
11 changes: 9 additions & 2 deletions src/middlewares/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { RateLimiterRes } from 'rate-limiter-flexible';

import { AbstractMiddleware, RateLimitConfig } from '../types';

export class RateLimitMiddleware<S extends Record<string, any>, C extends RateLimitConfig> extends AbstractMiddleware<S, C> {
export class RateLimitMiddleware<S extends Record<string, any>, C extends RateLimitConfig> extends AbstractMiddleware<
S,
C
> {
static throwAuthError(): never {
throw new VError('Auth Key Required', VError.HTTP_STATUS.UNAUTHORIZED);
}
Expand All @@ -19,7 +22,11 @@ export class RateLimitMiddleware<S extends Record<string, any>, C extends RateLi
return !req.headers.authorization;
}

async consume(res: Response, next: NextFunction, { resource, isPublic }: { resource: string; isPublic?: boolean }): Promise<void> {
async consume(
res: Response,
next: NextFunction,
{ resource, isPublic }: { resource: string; isPublic?: boolean }
): Promise<void> {
const maxPoints = isPublic ? this.config.RATE_LIMITER_POINTS_PUBLIC : this.config.RATE_LIMITER_POINTS_PRIVATE;
const rateLimiterClient = this.services.rateLimitClient[isPublic ? 'public' : 'private'];

Expand Down
10 changes: 8 additions & 2 deletions src/responseBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,11 @@ class ResponseBuilder {
req?: Request & { user?: { id: number } }
): ErrorResponse<T> {
if (error && (error as any).isAxiosError) {
log.error(`@backend-utils:errorResponse - error:axios:${JSON.stringify(ResponseBuilder.getAxiosError(error as AxiosError))}`);
log.error(
`@backend-utils:errorResponse - error:axios:${JSON.stringify(
ResponseBuilder.getAxiosError(error as AxiosError)
)}`
);
}

if (!(error instanceof Error)) {
Expand Down Expand Up @@ -198,7 +202,9 @@ class ResponseBuilder {
let output: ErrorResponse<unknown> | ReturnType<typeof ResponseBuilder['okResponse']>;

try {
const data = await (typeof dataPromise === 'function' ? (dataPromise as any)(req, res, nextCheck) : dataPromise);
const data = await (typeof dataPromise === 'function'
? (dataPromise as any)(req, res, nextCheck)
: dataPromise);

output =
data instanceof Error
Expand Down
6 changes: 5 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ export abstract class AbstractMiddleware<S extends Record<string, any>, C extend
constructor(public services: S, public config: C) {}
}

export abstract class AbstractManager<S extends Record<string, any>, C extends Record<string, any>, U extends Record<string, any> = {}> {
export abstract class AbstractManager<
S extends Record<string, any>,
C extends Record<string, any>,
U extends Record<string, any> = {}
> {
services: S & U;

constructor(services: S, public config: C) {
Expand Down
4 changes: 3 additions & 1 deletion tests/middlewares/rateLimit.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ describe('rateLimit middleware unit tests', () => {
const resource = 'version-id';
const res = { setHeader: sinon.stub() };

await expect(service.consume(res as any, next, { isPublic: true, resource })).to.eventually.rejectedWith('Too Many Request');
await expect(service.consume(res as any, next, { isPublic: true, resource })).to.eventually.rejectedWith(
'Too Many Request'
);

expect(services.rateLimitClient.public.consume.args).to.eql([[resource]]);
expect(res.setHeader.args).to.eql([['Retry-After', Math.floor(rateLimiterRes.msBeforeNext / 1000)]]);
Expand Down