Skip to content

Commit

Permalink
refactor(core): refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
darcyYe committed Mar 6, 2024
1 parent 0f0247c commit f4a812a
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 35 deletions.
1 change: 1 addition & 0 deletions packages/core/src/libraries/cloud-connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const logtoConfigs: LogtoConfigLibrary = {
resource: 'resource',
}),
getOidcConfigs: jest.fn(),
upsertJwtCustomizer: jest.fn(),
};

describe('getAccessToken()', () => {
Expand Down
24 changes: 21 additions & 3 deletions packages/core/src/libraries/logto-config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import type { LogtoOidcConfigType } from '@logto/schemas';
import {
cloudApiIndicator,
cloudConnectionDataGuard,
logtoOidcConfigGuard,
LogtoOidcConfigKey,
jwtCustomizerConfigGuard,
} from '@logto/schemas';
import type { LogtoOidcConfigType, LogtoJwtTokenKey } from '@logto/schemas';
import chalk from 'chalk';
import { z, ZodError } from 'zod';

Expand All @@ -14,7 +15,11 @@ import { consoleLog } from '#src/utils/console.js';
export type LogtoConfigLibrary = ReturnType<typeof createLogtoConfigLibrary>;

export const createLogtoConfigLibrary = ({
logtoConfigs: { getRowsByKeys, getCloudConnectionData: queryCloudConnectionData },
logtoConfigs: {
getRowsByKeys,
getCloudConnectionData: queryCloudConnectionData,
upsertJwtCustomizer: queryUpsertJwtCustomizer,
},
}: Pick<Queries, 'logtoConfigs'>) => {
const getOidcConfigs = async (): Promise<LogtoOidcConfigType> => {
try {
Expand Down Expand Up @@ -59,5 +64,18 @@ export const createLogtoConfigLibrary = ({
};
};

return { getOidcConfigs, getCloudConnectionData };
// Can not narrow down the type of value if we utilize `buildInsertIntoWithPool` method.
const upsertJwtCustomizer = async <T extends LogtoJwtTokenKey>(
key: T,
value: z.infer<(typeof jwtCustomizerConfigGuard)[T]>
) => {
const { value: rawValue } = await queryUpsertJwtCustomizer(key, value);

return {
key,
value: jwtCustomizerConfigGuard[key].parse(rawValue),
};
};

return { getOidcConfigs, getCloudConnectionData, upsertJwtCustomizer };
};
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const cloudConnection = createCloudConnectionLibrary({
resource: 'resource',
}),
getOidcConfigs: jest.fn(),
upsertJwtCustomizer: jest.fn(),
});

const getLogtoConnectors = jest.spyOn(connectorLibrary, 'getLogtoConnectors');
Expand Down
35 changes: 21 additions & 14 deletions packages/core/src/middleware/koa-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,27 +92,34 @@ export const isGuardMiddleware = <Type extends IMiddleware>(
): function_ is WithGuardConfig<Type> =>
function_.name === 'guardMiddleware' && has(function_, 'config');

export function tryParse<Output, Definition extends ZodTypeDef, Input>(
/**
* 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>,
data: unknown
): 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
) {
) => {
try {
return guard?.parse(data);
return guard.parse(data);
} catch (error: unknown) {
throw new RequestError({ code: 'guard.invalid_input', type }, error);
}
}
};

const tryParse = <Output, Definition extends ZodTypeDef, Input>(
type: 'query' | 'body' | 'params' | 'files',
guard: Optional<ZodType<Output, Definition, Input>>,
data: unknown
) => {
if (!guard) {
return;
}

return parse(type, guard, data);
};

export default function koaGuard<
StateT,
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/queries/logto-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
type LogtoOidcConfigKey,
type OidcConfigKey,
type LogtoJwtTokenKey,
type JwtCustomizerType,
} from '@logto/schemas';
import { convertToIdentifiers } from '@logto/shared';
import type { CommonQueryMethods } from 'slonik';
Expand Down Expand Up @@ -57,7 +56,7 @@ export const createLogtoConfigQueries = (pool: CommonQueryMethods) => {
key: T,
value: z.infer<(typeof jwtCustomizerConfigGuard)[T]>
) =>
pool.one<{ key: T; value: JwtCustomizerType[T] }>(
pool.one<{ key: T; value: Record<string, string> }>(
sql`
insert into ${table} (${fields.key}, ${fields.value})
values (${key}, ${sql.jsonb(value)})
Expand Down
11 changes: 6 additions & 5 deletions packages/core/src/routes/logto-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,15 @@ const logtoConfigQueries = {
}),
updateOidcConfigsByKey: jest.fn(),
getRowsByKeys: jest.fn(async () => mockLogtoConfigRows),
upsertJwtCustomizer: jest.fn(),
// UpsertJwtCustomizer: jest.fn(),
};

const logtoConfigLibraries = {
getOidcConfigs: jest.fn(async () => ({
[LogtoOidcConfigKey.PrivateKeys]: mockPrivateKeys,
[LogtoOidcConfigKey.CookieKeys]: mockCookieKeys,
})),
upsertJwtCustomizer: jest.fn(),
};

const settingRoutes = await pickDefault(import('./logto-config.js'));
Expand Down Expand Up @@ -232,13 +233,13 @@ describe('configs routes', () => {
rows: [],
rowCount: 0,
});
logtoConfigQueries.upsertJwtCustomizer.mockResolvedValueOnce(
logtoConfigLibraries.upsertJwtCustomizer.mockResolvedValueOnce(
mockJwtCustomizerConfigForAccessToken
);
const response = await routeRequester
.put(`/configs/jwt-customizer/access-token`)
.send(mockJwtCustomizerConfigForAccessToken.value);
expect(logtoConfigQueries.upsertJwtCustomizer).toHaveBeenCalledWith(
expect(logtoConfigLibraries.upsertJwtCustomizer).toHaveBeenCalledWith(
LogtoJwtTokenKey.AccessToken,
mockJwtCustomizerConfigForAccessToken.value
);
Expand All @@ -252,13 +253,13 @@ describe('configs routes', () => {
rows: [mockJwtCustomizerConfigForAccessToken],
rowCount: 1,
});
logtoConfigQueries.upsertJwtCustomizer.mockResolvedValueOnce(
logtoConfigLibraries.upsertJwtCustomizer.mockResolvedValueOnce(
mockJwtCustomizerConfigForAccessToken
);
const response = await routeRequester
.put('/configs/jwt-customizer/access-token')
.send(mockJwtCustomizerConfigForAccessToken.value);
expect(logtoConfigQueries.upsertJwtCustomizer).toHaveBeenCalledWith(
expect(logtoConfigLibraries.upsertJwtCustomizer).toHaveBeenCalledWith(
LogtoJwtTokenKey.AccessToken,
mockJwtCustomizerConfigForAccessToken.value
);
Expand Down
17 changes: 6 additions & 11 deletions packages/core/src/routes/logto-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
import { z } from 'zod';

import RequestError from '#src/errors/RequestError/index.js';
import koaGuard, { tryParse } from '#src/middleware/koa-guard.js';
import koaGuard, { parse } from '#src/middleware/koa-guard.js';
import { exportJWK } from '#src/utils/jwks.js';

import type { AuthedRouter, RouterInitArgs } from './types.js';
Expand All @@ -41,12 +41,12 @@ const getJwtTokenKeyAndBody = (tokenPath: LogtoJwtTokenPath, body: unknown) => {
if (tokenPath === LogtoJwtTokenPath.AccessToken) {
return {
key: LogtoJwtTokenKey.AccessToken,
body: tryParse('body', jwtCustomizerAccessTokenGuard, body),
body: parse('body', jwtCustomizerAccessTokenGuard, body),
};
}
return {
key: LogtoJwtTokenKey.ClientCredentials,
body: tryParse('body', jwtCustomizerClientCredentialsGuard, body),
body: parse('body', jwtCustomizerClientCredentialsGuard, body),
};
};

Expand Down Expand Up @@ -81,14 +81,9 @@ const getRedactedOidcKeyResponse = async (
export default function logtoConfigRoutes<T extends AuthedRouter>(
...[router, { queries, logtoConfigs, invalidateCache }]: RouterInitArgs<T>
) {
const {
getAdminConsoleConfig,
getRowsByKeys,
upsertJwtCustomizer,
updateAdminConsoleConfig,
updateOidcConfigsByKey,
} = queries.logtoConfigs;
const { getOidcConfigs } = logtoConfigs;
const { getAdminConsoleConfig, getRowsByKeys, updateAdminConsoleConfig, updateOidcConfigsByKey } =
queries.logtoConfigs;
const { getOidcConfigs, upsertJwtCustomizer } = logtoConfigs;

router.get(
'/configs/admin-console',
Expand Down

0 comments on commit f4a812a

Please sign in to comment.