Skip to content

Instantly share code, notes, and snippets.

@hos
Last active August 8, 2024 13:39
Show Gist options
  • Save hos/3f698ba78b2df6b797090ee04ae4115e to your computer and use it in GitHub Desktop.
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.
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