Skip to content

Commit

Permalink
Merge pull request #8 from flasd/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
flasd committed Mar 25, 2020
2 parents 9d38de6 + be928f7 commit 13586d8
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions src/index.ts
Expand Up @@ -5,19 +5,19 @@ import {
ObjectSchemaDefinition,
Schema,
ValidateOptions,
ObjectSchema,
// Its a peer dependency!
// eslint-disable-next-line import/no-unresolved
} from 'yup';

import {
Request, Response, NextFunction,
Request, Response, NextFunction, request,
// Its a peer dependency!
// eslint-disable-next-line import/no-unresolved
} from 'express';
import deepmerge from 'deepmerge';
import get from 'lodash.get';


type ResponseOptions = {
errorCode?: number;
returnErrors?: boolean;
Expand All @@ -32,7 +32,7 @@ export type ExpressYupMiddlewareOptions = {
transformEntity?: (entity: any) => any
}

export interface ExpressYupMiddleware {
export interface ExpressYupMiddleware<T> {
(req: Request, res: Response, next: NextFunction): Promise<void>
}

Expand All @@ -51,15 +51,15 @@ const defaults: ExpressYupMiddlewareOptions = {
entityFrom: 'body',
};

function getSchema(
schema: Schema<any> | ObjectSchemaDefinition<object>,
function getSchema<T>(
schema: Schema<T> | ObjectSchemaDefinition<object & T>,
validateOptions: ValidateOptions,
) {
): Schema<T> | ObjectSchema<object & T> {
if (isSchema(schema)) {
return schema;
return schema as Schema<T>;
}

return object(schema).strict(validateOptions.strict);
return object<object & T>(schema).strict(validateOptions.strict);
}

function getEntity(req: Request, configs: ExpressYupMiddlewareOptions): any {
Expand All @@ -76,11 +76,27 @@ function getEntity(req: Request, configs: ExpressYupMiddlewareOptions): any {
}
}

function is<T>(it: any): it is T {
return it;
}

function typeGuard<T>(
req: Request,
config: ExpressYupMiddlewareOptions,
) {
const { entityFrom, entityPath } = config;

if (entityFrom !== 'request') {
return is<T>(req[entityFrom]);
}

export default function createValidation(
schema: Schema<any> | any,
return get(request, entityPath) as T;
}

export default function createValidation<T>(
schema: Schema<T> | ObjectSchemaDefinition<object & T>,
options?: ExpressYupMiddlewareOptions,
): ExpressYupMiddleware {
): ExpressYupMiddleware<T> {
const configs: ExpressYupMiddlewareOptions = deepmerge(
defaults,
options || {},
Expand All @@ -99,6 +115,8 @@ export default function createValidation(
await finalSchema
.validate(entity, configs.validateOptions);

typeGuard(req, configs);

next();
} catch (error) {
if (!(error instanceof ValidationError)) {
Expand Down

0 comments on commit 13586d8

Please sign in to comment.