0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-06 20:40:08 -05:00
logto/packages/core/src/database/utils.ts

34 lines
1 KiB
TypeScript
Raw Normal View History

2021-07-04 04:41:46 -05:00
import { IdentifierSqlTokenType, sql, ValueExpressionType } from 'slonik';
2021-06-23 12:09:42 -05:00
type Table = { table: string; fields: Record<string, string> };
type FieldIdentifiers<Key extends string | number | symbol> = {
[key in Key]: IdentifierSqlTokenType;
};
2021-06-25 12:39:02 -05:00
export const convertToIdentifiers = <T extends Table>(
{ table, fields }: T,
withPrefix = false
) => ({
2021-06-23 12:09:42 -05:00
table: sql.identifier([table]),
fields: Object.entries<string>(fields).reduce(
2021-06-25 12:39:02 -05:00
(previous, [key, value]) => ({
...previous,
[key]: sql.identifier(withPrefix ? [table, value] : [value]),
}),
2021-06-23 12:09:42 -05:00
// eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter
{} as FieldIdentifiers<keyof T['fields']>
),
});
2021-07-04 04:41:46 -05:00
export const insertInto = <T extends string>(
table: IdentifierSqlTokenType,
fields: FieldIdentifiers<T>,
fieldKeys: readonly T[],
value: { [key in T]?: ValueExpressionType }
) => sql`
insert into ${table} (${sql.join(Object.values(fields), sql`, `)})
values (${sql.join(
fieldKeys.map((key) => value[key] ?? null),
sql`, `
)})`;