Skip to content

Commit

Permalink
refactor(core): refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
darcyYe committed Mar 6, 2024
1 parent 44ff452 commit 5d8e685
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 32 deletions.
5 changes: 5 additions & 0 deletions packages/core/src/middleware/koa-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ 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>(
type: 'query' | 'body' | 'params' | 'files',
guard: ZodType<Output, Definition, Input>,
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/queries/logto-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <T extends LogtoJwtTokenKey>(
const upsertJwtCustomizer = async <T extends LogtoJwtTokenKey>(
key: T,
value: z.infer<(typeof jwtCustomizerConfigGuard)[T]>
) =>
Expand All @@ -74,6 +74,6 @@ export const createLogtoConfigQueries = (pool: CommonQueryMethods) => {
getCloudConnectionData,
getRowsByKeys,
updateOidcConfigsByKey,
insertOrUpdateJwtCustomizer,
upsertJwtCustomizer,
};
};
10 changes: 5 additions & 5 deletions packages/core/src/routes/logto-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const logtoConfigQueries = {
}),
updateOidcConfigsByKey: jest.fn(),
getRowsByKeys: jest.fn(async () => mockLogtoConfigRows),
insertOrUpdateJwtCustomizer: jest.fn(),
upsertJwtCustomizer: jest.fn(),
};

const logtoConfigLibraries = {
Expand Down Expand Up @@ -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
);
Expand All @@ -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
);
Expand Down
29 changes: 13 additions & 16 deletions packages/core/src/routes/logto-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
};

/**
Expand Down Expand Up @@ -86,7 +84,7 @@ export default function logtoConfigRoutes<T extends AuthedRouter>(
const {
getAdminConsoleConfig,
getRowsByKeys,
insertOrUpdateJwtCustomizer,
upsertJwtCustomizer,
updateAdminConsoleConfig,
updateOidcConfigsByKey,
} = queries.logtoConfigs;
Expand Down Expand Up @@ -233,12 +231,11 @@ export default function logtoConfigRoutes<T extends AuthedRouter>(
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;
Expand Down
2 changes: 1 addition & 1 deletion packages/integration-tests/src/api/logto-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const rotateOidcKeys = async (
.post(`configs/oidc/${keyType}/rotate`, { json: { signingKeyAlgorithm } })
.json<OidcConfigKeysResponse[]>();

export const insertOrUpdateJwtCustomizer = async (
export const upsertJwtCustomizer = async (
keyTypePath: 'access-token' | 'client-credentials',
value: unknown
) =>
Expand Down
13 changes: 5 additions & 8 deletions packages/integration-tests/src/tests/api/logto-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
getOidcKeys,
rotateOidcKeys,
updateAdminConsoleConfig,
insertOrUpdateJwtCustomizer,
upsertJwtCustomizer,
} from '#src/api/index.js';
import { expectRejects } from '#src/helpers/index.js';

Expand Down Expand Up @@ -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
);
Expand All @@ -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
);
Expand Down

0 comments on commit 5d8e685

Please sign in to comment.