({
query,
body,
params,
response,
status,
files,
}: GuardConfig<
GuardQueryT,
GuardBodyT,
GuardParametersT,
GuardResponseT,
GuardFilesT
>)
| 128 | * Note: A context-aware console log is required to be present in the context (i.e. `ctx.console`). |
| 129 | */ |
| 130 | export default function koaGuard< |
| 131 | StateT, |
| 132 | ContextT extends IRouterParamContext, |
| 133 | GuardQueryT = undefined, |
| 134 | GuardBodyT = undefined, |
| 135 | GuardParametersT = undefined, |
| 136 | GuardResponseT = unknown, |
| 137 | GuardFilesT = undefined, |
| 138 | >({ |
| 139 | query, |
| 140 | body, |
| 141 | params, |
| 142 | response, |
| 143 | status, |
| 144 | files, |
| 145 | }: GuardConfig< |
| 146 | GuardQueryT, |
| 147 | GuardBodyT, |
| 148 | GuardParametersT, |
| 149 | GuardResponseT, |
| 150 | GuardFilesT |
| 151 | >): MiddlewareType< |
| 152 | StateT, |
| 153 | WithGuardedRequestContext<ContextT, GuardQueryT, GuardBodyT, GuardParametersT, GuardFilesT>, |
| 154 | GuardResponseT |
| 155 | > { |
| 156 | const guard: MiddlewareType< |
| 157 | StateT, |
| 158 | WithGuardedRequestContext<ContextT, GuardQueryT, GuardBodyT, GuardParametersT, GuardFilesT>, |
| 159 | GuardResponseT |
| 160 | > = async (ctx, next) => { |
| 161 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, no-restricted-syntax |
| 162 | ctx.guard = { |
| 163 | query: tryParse('query', query, ctx.request.query), |
| 164 | body: tryParse('body', body, ctx.request.body ?? {}), // Fallback to empty object since it's the original behavior of koa-body@5 |
| 165 | params: tryParse('params', params, ctx.params), |
| 166 | files: tryParse('files', files, ctx.request.files), |
| 167 | } as GuardedRequest<GuardQueryT, GuardBodyT, GuardParametersT, GuardFilesT>; // Have to do this since it's too complicated for TS |
| 168 | |
| 169 | return next(); |
| 170 | }; |
| 171 | |
| 172 | const guardMiddleware: WithGuardConfig< |
| 173 | MiddlewareType< |
| 174 | StateT, |
| 175 | WithGuardedRequestContext<ContextT, GuardQueryT, GuardBodyT, GuardParametersT, GuardFilesT>, |
| 176 | GuardResponseT |
| 177 | > |
| 178 | > = async function (ctx, next) { |
| 179 | const consoleLog = getConsoleLogFromContext(ctx); |
| 180 | |
| 181 | /** |
| 182 | * Assert the status code matches the value(s) in the config. If the config does not |
| 183 | * specify a status code, it will not assert anything. |
| 184 | * |
| 185 | * In production, it will log a warning if the status code does not match the value(s) in the |
| 186 | * config for better user experience. |
| 187 | * |
no outgoing calls
no test coverage detected