2021-06-23 12:09:42 -05:00
|
|
|
import { IdentifierSqlTokenType, sql } from 'slonik';
|
|
|
|
|
|
|
|
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']>
|
|
|
|
),
|
|
|
|
});
|