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`, `
|
|
|
|
)})`;
|