Last active
August 8, 2024 13:39
-
-
Save hos/3f698ba78b2df6b797090ee04ae4115e to your computer and use it in GitHub Desktop.
Typed function to use with knex tables, to remove some columns from provided object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'types/schemas/knex-tables' | |
import { Tables } from 'knex/types/tables' | |
type TableColumns<TTableName extends keyof Tables = keyof Tables> = { | |
[T in TTableName]: (keyof Tables[T]['base'])[] | |
} | |
const deleteColumns: Partial<TableColumns> = { | |
users: ['name'], | |
} | |
export function clipColumns< | |
TTableName extends keyof Tables, | |
TRecord extends Tables[TTableName]['insert'] | Tables[TTableName]['update'], | |
>(tableName: TTableName, record: TRecord | TRecord[]): TRecord | TRecord[] { | |
const columnsToRemove = deleteColumns[tableName] || [] | |
const clipSingleRecord = (rec: TRecord): TRecord => { | |
const result = { ...rec } | |
for (const column of columnsToRemove) { | |
delete result[column] | |
} | |
return result | |
} | |
if (Array.isArray(record)) { | |
return record.map(clipSingleRecord) | |
} else { | |
return clipSingleRecord(record) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment