Skip to content

Commit

Permalink
feat: add a default value for the ctx.validatedData (#287)
Browse files Browse the repository at this point in the history
* feat: update regex validations

* feat: add default value for the validatedData

* refactor: add empty line
  • Loading branch information
ilyevskii committed Mar 25, 2024
1 parent 38fe9cf commit ce5b07e
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
2 changes: 2 additions & 0 deletions template/apps/api/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import { AppKoa } from 'types';
import tryToAttachUser from './middlewares/try-to-attach-user.middleware';
import extractTokens from './middlewares/extract-tokens.middleware';
import attachCustomErrors from './middlewares/attach-custom-errors.middleware';
import attachCustomProperties from './middlewares/attach-custom-properties.middleware';
import routeErrorHandler from './middlewares/route-error-handler.middleware';
import publicRoutes from './public.routes';
import privateRoutes from './private.routes';
import adminRoutes from './admin.routes';

const defineRoutes = (app: AppKoa) => {
app.use(attachCustomErrors);
app.use(attachCustomProperties);
app.use(routeErrorHandler);
app.use(extractTokens);
app.use(tryToAttachUser);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { AppKoaContext, Next } from 'types';

const attachCustomProperties = async (ctx: AppKoaContext, next: Next) => {
ctx.validatedData = {};

await next();
};

export default attachCustomProperties;
2 changes: 1 addition & 1 deletion template/apps/api/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export type CustomErrors = {

export interface AppKoaContext<T = unknown, R = unknown> extends ParameterizedContext<AppKoaContextState> {
request: Request & R;
validatedData: T;
validatedData: T & object;
throwError: (message: string) => never;
assertError: (condition: unknown, message: string) => asserts condition;
throwClientError: (errors: CustomErrors, status?: number) => never;
Expand Down

1 comment on commit ce5b07e

@ilyevskii
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This PR fixes problems when we need to pass some value from a validator to a handler in a controller. Without this fix, if validateMiddleware is not used in a controller, when trying to do the following:

ctx.validatedData.user = user;

we'll get an error that ctx.validatedData is undefined.

Please sign in to comment.