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(work-standard): added linters #2

Merged
merged 6 commits into from
Aug 3, 2020
Merged
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
6 changes: 0 additions & 6 deletions .prettierrc.json

This file was deleted.

1 change: 1 addition & 0 deletions commitlint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = { extends: ['@commitlint/config-conventional'] };
5 changes: 5 additions & 0 deletions mc-model-types/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

### 1.0.1 (2020-08-03)
14 changes: 6 additions & 8 deletions mc-model-types/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@map-colonies/mc-model-types",
"version": "1.0.0",
"version": "1.0.1",
"description": "json schemas for validations and generated ts models",
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
Expand All @@ -15,19 +15,17 @@
"scripts": {
"prepare": "npm run build",
"build": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json",
"clean": "rimraf lib && rimraf *.tgz"
"clean": "rimraf lib && rimraf *.tgz",
"release": "standard-version -t mc-model-types@"
},
"author": "",
"license": "ISC",
"devDependencies": {
"rimraf": "^3.0.2",
"typescript": "^3.9.7"
"typescript": "^3.9.7",
"standard-version": "^8.0.2"
},
"files": [
"lib/**/*"
],
"dependencies": {
"ajv": "^6.12.3",
"axios": "^0.19.2"
}
]
}
24 changes: 24 additions & 0 deletions mc-nest-schema-validator/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "tsconfig.json",
"sourceType": "module"
},
"plugins": ["@typescript-eslint/eslint-plugin"],
"extends": [
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"prettier",
"prettier/@typescript-eslint"
],
"root": true,
"env": {
"node": true,
"jest": true
},
"rules": {
"@typescript-eslint/interface-name-prefix": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-explicit-any": "off"
}
}
5 changes: 5 additions & 0 deletions mc-nest-schema-validator/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

### 1.0.1 (2020-08-03)
22 changes: 18 additions & 4 deletions mc-nest-schema-validator/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@map-colonies/mc-nest-schema-validator",
"version": "1.0.0",
"version": "1.0.1",
"description": "nest module for validating json schema",
"main": "lib/cjs/index.js",
"module": "lib/esm/index.js",
Expand All @@ -14,14 +14,18 @@
},
"scripts": {
"build": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json",
"prepare": "install-peers && npm run build"
"prepare": "install-peers && npm run build",
"lint": "eslint ./src/**",
"lint:fix": "eslint --fix ./src/**",
"release": "standard-version -t mc-nest-schema-validator@",
"install-peers": "install-peers"
},
"author": "",
"license": "ISC",
"dependencies": {
"@map-colonies/mc-schema-validator": "^1.0.1",
"class-validator": "^0.12.2",
"config": "^3.3.1",
"mc-schema-validator": "1.0.0",
"typescript": "^3.9.7"
},
"peerDependencies": {
Expand All @@ -35,6 +39,16 @@
],
"devDependencies": {
"@types/config": "0.0.36",
"install-peers-cli": "^2.2.0"
"@typescript-eslint/eslint-plugin": "^3.7.1",
"@typescript-eslint/parser": "^3.7.1",
"eslint": "^6.8.0",
"eslint-config-standard": "^14.1.1",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"install-peers-cli": "^2.2.0",
"nyc": "^15.1.0",
"standard-version": "^8.0.2"
}
}
12 changes: 7 additions & 5 deletions mc-nest-schema-validator/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { has, get } from 'config';

type Logger = {
log(level: string, message: string): void;
export type Logger = {
log: (level: string, message: string) => void;
};
export class config {
static schemaSourceRoot: string = has('validation.schemaSourceRoot')

export class Config {
public static schemaSourceRoot: string = has('validation.schemaSourceRoot')
? get<string>('validation.schemaSourceRoot')
: '';
static logger: Logger;

public static logger: Logger;
}
18 changes: 10 additions & 8 deletions mc-nest-schema-validator/src/swagger/BodySchema.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { ApiBody } from '@nestjs/swagger';
import { config } from '../config';
import { Config } from '../config';

export function BodySchema(schemaUrl: string): MethodDecorator {
if (!schemaUrl.match(/^http(s)?:\/\/.*/))
const httpRegex = /^http(s)?:\/\/.*/;
if (!httpRegex.exec(schemaUrl)) {
schemaUrl = schemaUrl.startsWith('/')
? config.schemaSourceRoot + schemaUrl
: config.schemaSourceRoot + '/' + schemaUrl;
? Config.schemaSourceRoot + schemaUrl
: Config.schemaSourceRoot + '/' + schemaUrl;
}

return ApiBody({
schema: {
allOf: [
{
$ref: schemaUrl,
},
],
},
$ref: schemaUrl
}
]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}
});
}
18 changes: 10 additions & 8 deletions mc-nest-schema-validator/src/swagger/ResponseSchema.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { ApiResponse } from '@nestjs/swagger';
import { config } from '../config';
import { Config } from '../config';

export function ResponseSchema(schemaUrl: string): MethodDecorator {
if (!schemaUrl.match(/^http(s)?:\/\/.*/))
const httpRegex = /^http(s)?:\/\/.*/;
if (!httpRegex.exec(schemaUrl)) {
schemaUrl = schemaUrl.startsWith('/')
? config.schemaSourceRoot + schemaUrl
: config.schemaSourceRoot + '/' + schemaUrl;
? Config.schemaSourceRoot + schemaUrl
: Config.schemaSourceRoot + '/' + schemaUrl;
}
return ApiResponse({
schema: {
allOf: [
{
$ref: schemaUrl,
},
],
},
$ref: schemaUrl
}
]
}
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,32 @@ import { registerDecorator, ValidationOptions } from 'class-validator';
import { SchemaValidatorConstraint } from './SchemaValidatorConstraint';
import { applyDecorators } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';
import { config } from '../config';
import { Config } from '../config';

export function PropertySchema(
schemaUrl: string,
validationOptions?: ValidationOptions
): PropertyDecorator {
if (!schemaUrl.match(/^http(s)?:\/\/.*/))
if (!schemaUrl.match(/^http(s)?:\/\/.*/)) {
schemaUrl = schemaUrl.startsWith('/')
? config.schemaSourceRoot + schemaUrl
: config.schemaSourceRoot + '/' + schemaUrl;
? Config.schemaSourceRoot + schemaUrl
: Config.schemaSourceRoot + '/' + schemaUrl;
}
return applyDecorators(
ApiProperty({
allOf: [
{
$ref: schemaUrl,
},
],
$ref: schemaUrl
}
]
}),
function (object: unknown, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
constraints: [schemaUrl],
validator: SchemaValidatorConstraint,
validator: SchemaValidatorConstraint
});
}
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
ValidationArguments,
ValidatorConstraint,
ValidatorConstraintInterface,
ValidatorConstraintInterface
} from 'class-validator';
import { SchemaValidator, ValidationStatus } from 'mc-schema-validator';
import { SchemaValidator, ValidationStatus } from '@map-colonies/mc-schema-validator';
import { BadRequestException, Injectable } from '@nestjs/common';
import Ajv from 'ajv';

Expand All @@ -12,7 +12,7 @@ import Ajv from 'ajv';
export class SchemaValidatorConstraint implements ValidatorConstraintInterface {
private errors?: Ajv.ErrorObject[];

async validate(
public async validate(
value: unknown,
validationArguments?: ValidationArguments
): Promise<boolean> {
Expand All @@ -21,9 +21,11 @@ export class SchemaValidatorConstraint implements ValidatorConstraintInterface {
value
);
this.errors = res.errors;
return res.status == ValidationStatus.valid;
return res.status === ValidationStatus.valid;
}
defaultMessage?(validationArguments?: ValidationArguments): string {

//eslint-disable-next-line @typescript-eslint/no-unused-vars
public defaultMessage?(validationArguments?: ValidationArguments): string {
throw new BadRequestException(this.errors);
}
}
21 changes: 11 additions & 10 deletions mc-nest-schema-validator/src/validation/ValidationInterceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,24 @@ import {
InternalServerErrorException,
Injectable,
NestInterceptor,
CallHandler,
CallHandler
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { SchemaValidator, ValidationStatus } from 'mc-schema-validator';
import { SchemaValidator, ValidationStatus } from '@map-colonies/mc-schema-validator';
import { Observable } from 'rxjs';
import { ISchemaOptions } from './ISchemaOptions';
import { config } from '../config';
import { Config } from '../config';

@Injectable()
export class ValidationInterceptor implements NestInterceptor {
constructor(
private reflector: Reflector,
private validator: SchemaValidator
private readonly reflector: Reflector,
private readonly validator: SchemaValidator
) {}

async intercept(
context: ExecutionContext,
next: CallHandler<any>
next: CallHandler
): Promise<Observable<any>> {
let validationErrors: unknown;
try {
Expand Down Expand Up @@ -49,7 +49,7 @@ export class ValidationInterceptor implements NestInterceptor {
try {
data[key] = JSON.parse(data[key]);
} catch (err) {
config.logger?.log('info', `invalid json: ${err.message}`);
Config.logger.log('info', `invalid json: ${err.message}`);
validationErrors = err;
}
});
Expand All @@ -58,15 +58,16 @@ export class ValidationInterceptor implements NestInterceptor {
if (!validationErrors) {
const res = await this.validator.validate(schema, data);
if (res.status == ValidationStatus.valid) return next.handle();
else if (res.status == ValidationStatus.missingValidator)
config.logger?.log(
else if (res.status == ValidationStatus.missingValidator) {
Config.logger.log(
'warn',
`no validator was registered for: ${schema}`
);
}
validationErrors = res.errors;
}
} catch (err) {
config.logger?.log('error', `validation schema error: ${err}`);
Config.logger.log('error', `validation schema error: ${err}`);
throw new InternalServerErrorException();
}
throw new BadRequestException(validationErrors);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { SetMetadata, applyDecorators, UseInterceptors } from '@nestjs/common';
import { ValidationInterceptor } from './ValidationInterceptor';
import { ISchemaOptions } from './ISchemaOptions';
import { BodySchema } from '../swagger/BodySchema.decorator';
import { config } from '../config';
import { Config } from '../config';

export function ValidationSchema(schemaOpt: string | ISchemaOptions) {
export function ValidationSchema(schemaOpt: string | ISchemaOptions) : ClassDecorator | MethodDecorator | PropertyDecorator {
let schemaUrl = typeof schemaOpt === 'string' ? schemaOpt : schemaOpt.schema;
schemaUrl = schemaUrl.startsWith('/')
? config.schemaSourceRoot + schemaUrl
: config.schemaSourceRoot + '/' + schemaUrl;
if (typeof schemaOpt != 'string') schemaOpt.schema = schemaUrl;
? Config.schemaSourceRoot + schemaUrl
: Config.schemaSourceRoot + '/' + schemaUrl;
if (typeof schemaOpt !== 'string') schemaOpt.schema = schemaUrl;
const decorators: (MethodDecorator | ClassDecorator | PropertyDecorator)[] = [
BodySchema(schemaUrl),
SetMetadata('ValidatorSchema', schemaOpt),
SetMetadata('ValidatorSchema', schemaOpt)
];
if (
typeof schemaOpt === 'string' ||
schemaOpt.registerInterceptor == null ||
schemaOpt.registerInterceptor == true
schemaOpt.registerInterceptor
) {
decorators.push(UseInterceptors(ValidationInterceptor));
}
Expand Down
Loading