From 5d8e6853d179ae8803e36e0fb54a28268fbb3e6b Mon Sep 17 00:00:00 2001 From: Darcy Ye Date: Wed, 6 Mar 2024 17:16:21 +0800 Subject: [PATCH] refactor(core): refactor code --- packages/core/src/middleware/koa-guard.ts | 5 ++++ packages/core/src/queries/logto-config.ts | 4 +-- packages/core/src/routes/logto-config.test.ts | 10 +++---- packages/core/src/routes/logto-config.ts | 29 +++++++++---------- .../integration-tests/src/api/logto-config.ts | 2 +- .../src/tests/api/logto-config.test.ts | 13 ++++----- 6 files changed, 31 insertions(+), 32 deletions(-) diff --git a/packages/core/src/middleware/koa-guard.ts b/packages/core/src/middleware/koa-guard.ts index 2deb09d8c..d1e56c607 100644 --- a/packages/core/src/middleware/koa-guard.ts +++ b/packages/core/src/middleware/koa-guard.ts @@ -92,6 +92,11 @@ export const isGuardMiddleware = ( ): function_ is WithGuardConfig => 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 = ( type: 'query' | 'body' | 'params' | 'files', guard: ZodType, diff --git a/packages/core/src/queries/logto-config.ts b/packages/core/src/queries/logto-config.ts index a7cabae10..14f0b8c67 100644 --- a/packages/core/src/queries/logto-config.ts +++ b/packages/core/src/queries/logto-config.ts @@ -53,7 +53,7 @@ export const createLogtoConfigQueries = (pool: CommonQueryMethods) => { `); // Can not narrow down the type of value if we utilize `buildInsertIntoWithPool` method. - const insertOrUpdateJwtCustomizer = async ( + const upsertJwtCustomizer = async ( key: T, value: z.infer<(typeof jwtCustomizerConfigGuard)[T]> ) => @@ -74,6 +74,6 @@ export const createLogtoConfigQueries = (pool: CommonQueryMethods) => { getCloudConnectionData, getRowsByKeys, updateOidcConfigsByKey, - insertOrUpdateJwtCustomizer, + upsertJwtCustomizer, }; }; diff --git a/packages/core/src/routes/logto-config.test.ts b/packages/core/src/routes/logto-config.test.ts index ce0dc9dc4..b82422b1a 100644 --- a/packages/core/src/routes/logto-config.test.ts +++ b/packages/core/src/routes/logto-config.test.ts @@ -54,7 +54,7 @@ const logtoConfigQueries = { }), updateOidcConfigsByKey: jest.fn(), getRowsByKeys: jest.fn(async () => mockLogtoConfigRows), - insertOrUpdateJwtCustomizer: jest.fn(), + upsertJwtCustomizer: jest.fn(), }; const logtoConfigLibraries = { @@ -232,13 +232,13 @@ describe('configs routes', () => { rows: [], rowCount: 0, }); - logtoConfigQueries.insertOrUpdateJwtCustomizer.mockResolvedValueOnce( + logtoConfigQueries.upsertJwtCustomizer.mockResolvedValueOnce( mockJwtCustomizerConfigForAccessToken ); const response = await routeRequester .put(`/configs/jwt-customizer/access-token`) .send(mockJwtCustomizerConfigForAccessToken.value); - expect(logtoConfigQueries.insertOrUpdateJwtCustomizer).toHaveBeenCalledWith( + expect(logtoConfigQueries.upsertJwtCustomizer).toHaveBeenCalledWith( LogtoJwtTokenKey.AccessToken, mockJwtCustomizerConfigForAccessToken.value ); @@ -252,13 +252,13 @@ describe('configs routes', () => { rows: [mockJwtCustomizerConfigForAccessToken], rowCount: 1, }); - logtoConfigQueries.insertOrUpdateJwtCustomizer.mockResolvedValueOnce( + logtoConfigQueries.upsertJwtCustomizer.mockResolvedValueOnce( mockJwtCustomizerConfigForAccessToken ); const response = await routeRequester .put('/configs/jwt-customizer/access-token') .send(mockJwtCustomizerConfigForAccessToken.value); - expect(logtoConfigQueries.insertOrUpdateJwtCustomizer).toHaveBeenCalledWith( + expect(logtoConfigQueries.upsertJwtCustomizer).toHaveBeenCalledWith( LogtoJwtTokenKey.AccessToken, mockJwtCustomizerConfigForAccessToken.value ); diff --git a/packages/core/src/routes/logto-config.ts b/packages/core/src/routes/logto-config.ts index 40d5d7cf3..94c8d3546 100644 --- a/packages/core/src/routes/logto-config.ts +++ b/packages/core/src/routes/logto-config.ts @@ -37,19 +37,17 @@ const getOidcConfigKeyDatabaseColumnName = (key: LogtoOidcConfigKeyType): LogtoO ? LogtoOidcConfigKey.PrivateKeys : LogtoOidcConfigKey.CookieKeys; -const getLogtoJwtTokenKey = (key: LogtoJwtTokenPath): LogtoJwtTokenKey => - key === LogtoJwtTokenPath.AccessToken - ? LogtoJwtTokenKey.AccessToken - : LogtoJwtTokenKey.ClientCredentials; - -const guardJwtCustomizerBody = (tokenTypePath: LogtoJwtTokenPath, body: unknown) => { - // Manually implement the request body type check, the flow aligns with the actual `koaGuard()`. - // Use ternary operator to get the specific guard brings difficulties to type inference. - if (tokenTypePath === LogtoJwtTokenPath.AccessToken) { - return parse('body', jwtCustomizerAccessTokenGuard, body); +const getJwtTokenKeyAndBody = (tokenPath: LogtoJwtTokenPath, body: unknown) => { + if (tokenPath === LogtoJwtTokenPath.AccessToken) { + return { + key: LogtoJwtTokenKey.AccessToken, + body: parse('body', jwtCustomizerAccessTokenGuard, body), + }; } - - return parse('body', jwtCustomizerClientCredentialsGuard, body); + return { + key: LogtoJwtTokenKey.ClientCredentials, + body: parse('body', jwtCustomizerClientCredentialsGuard, body), + }; }; /** @@ -86,7 +84,7 @@ export default function logtoConfigRoutes( const { getAdminConsoleConfig, getRowsByKeys, - insertOrUpdateJwtCustomizer, + upsertJwtCustomizer, updateAdminConsoleConfig, updateOidcConfigsByKey, } = queries.logtoConfigs; @@ -233,12 +231,11 @@ export default function logtoConfigRoutes( params: { tokenTypePath }, body: rawBody, } = ctx.guard; - const key = getLogtoJwtTokenKey(tokenTypePath); - const body = guardJwtCustomizerBody(tokenTypePath, rawBody); + const { key, body } = getJwtTokenKeyAndBody(tokenTypePath, rawBody); const { rows } = await getRowsByKeys([key]); - const jwtCustomizer = await insertOrUpdateJwtCustomizer(key, body); + const jwtCustomizer = await upsertJwtCustomizer(key, body); if (rows.length === 0) { ctx.status = 201; diff --git a/packages/integration-tests/src/api/logto-config.ts b/packages/integration-tests/src/api/logto-config.ts index 72ed8a1a8..9a0d6e319 100644 --- a/packages/integration-tests/src/api/logto-config.ts +++ b/packages/integration-tests/src/api/logto-config.ts @@ -33,7 +33,7 @@ export const rotateOidcKeys = async ( .post(`configs/oidc/${keyType}/rotate`, { json: { signingKeyAlgorithm } }) .json(); -export const insertOrUpdateJwtCustomizer = async ( +export const upsertJwtCustomizer = async ( keyTypePath: 'access-token' | 'client-credentials', value: unknown ) => diff --git a/packages/integration-tests/src/tests/api/logto-config.test.ts b/packages/integration-tests/src/tests/api/logto-config.test.ts index 2d4674431..0ce00c82f 100644 --- a/packages/integration-tests/src/tests/api/logto-config.test.ts +++ b/packages/integration-tests/src/tests/api/logto-config.test.ts @@ -10,7 +10,7 @@ import { getOidcKeys, rotateOidcKeys, updateAdminConsoleConfig, - insertOrUpdateJwtCustomizer, + upsertJwtCustomizer, } from '#src/api/index.js'; import { expectRejects } from '#src/helpers/index.js'; @@ -141,22 +141,19 @@ describe('admin console sign-in experience', () => { contextSample: {}, }; - const accessToken = await insertOrUpdateJwtCustomizer( - 'access-token', - accessTokenJwtCustomizerPayload - ); + const accessToken = await upsertJwtCustomizer('access-token', accessTokenJwtCustomizerPayload); expect(accessToken).toMatchObject(accessTokenJwtCustomizerPayload); const newAccessTokenJwtCustomizerPayload = { ...accessTokenJwtCustomizerPayload, script: 'new script', }; - const updatedAccessToken = await insertOrUpdateJwtCustomizer( + const updatedAccessToken = await upsertJwtCustomizer( 'access-token', newAccessTokenJwtCustomizerPayload ); expect(updatedAccessToken).toMatchObject(newAccessTokenJwtCustomizerPayload); - const clientCredentials = await insertOrUpdateJwtCustomizer( + const clientCredentials = await upsertJwtCustomizer( 'client-credentials', clientCredentialsJwtCustomizerPayload ); @@ -165,7 +162,7 @@ describe('admin console sign-in experience', () => { ...clientCredentialsJwtCustomizerPayload, script: 'new script client credentials', }; - const updatedClientCredentials = await insertOrUpdateJwtCustomizer( + const updatedClientCredentials = await upsertJwtCustomizer( 'client-credentials', newClientCredentialsJwtCustomizerPayload );