0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-02-17 22:04:19 -05:00

refactor(core): overload function interface

This commit is contained in:
Darcy Ye 2024-03-06 18:47:41 +08:00
parent 5d8e6853d1
commit 0f0247ce2f
No known key found for this signature in database
GPG key ID: B46F4C07EDEFC610
2 changed files with 17 additions and 23 deletions

View file

@ -92,33 +92,27 @@ export const isGuardMiddleware = <Type extends IMiddleware>(
): function_ is WithGuardConfig<Type> =>
function_.name === 'guardMiddleware' && has(function_, 'config');
/**
* Previous `tryParse` function's output type was `Output | undefined`.
* It can not properly infer the output type to be `Output` even if the guard is provided,
* which brings additional but unnecessary type checks.
*/
export const parse = <Output, Definition extends ZodTypeDef, Input>(
export function tryParse<Output, Definition extends ZodTypeDef, Input>(
type: 'query' | 'body' | 'params' | 'files',
guard: ZodType<Output, Definition, Input>,
data: unknown
) => {
try {
return guard.parse(data);
} catch (error: unknown) {
throw new RequestError({ code: 'guard.invalid_input', type }, error);
}
};
const tryParse = <Output, Definition extends ZodTypeDef, Input>(
): Output;
export function tryParse<Output, Definition extends ZodTypeDef, Input>(
type: 'query' | 'body' | 'params' | 'files',
guard: undefined,
data: unknown
): undefined;
export function tryParse<Output, Definition extends ZodTypeDef, Input>(
type: 'query' | 'body' | 'params' | 'files',
guard: Optional<ZodType<Output, Definition, Input>>,
data: unknown
) => {
if (!guard) {
return;
) {
try {
return guard?.parse(data);
} catch (error: unknown) {
throw new RequestError({ code: 'guard.invalid_input', type }, error);
}
return parse(type, guard, data);
};
}
export default function koaGuard<
StateT,

View file

@ -19,7 +19,7 @@ import {
import { z } from 'zod';
import RequestError from '#src/errors/RequestError/index.js';
import koaGuard, { parse } from '#src/middleware/koa-guard.js';
import koaGuard, { tryParse } from '#src/middleware/koa-guard.js';
import { exportJWK } from '#src/utils/jwks.js';
import type { AuthedRouter, RouterInitArgs } from './types.js';
@ -41,12 +41,12 @@ const getJwtTokenKeyAndBody = (tokenPath: LogtoJwtTokenPath, body: unknown) => {
if (tokenPath === LogtoJwtTokenPath.AccessToken) {
return {
key: LogtoJwtTokenKey.AccessToken,
body: parse('body', jwtCustomizerAccessTokenGuard, body),
body: tryParse('body', jwtCustomizerAccessTokenGuard, body),
};
}
return {
key: LogtoJwtTokenKey.ClientCredentials,
body: parse('body', jwtCustomizerClientCredentialsGuard, body),
body: tryParse('body', jwtCustomizerClientCredentialsGuard, body),
};
};