Last active
September 28, 2024 12:14
-
-
Save demirtasdurmus/50962a878e6c626c5028f59aa5861243 to your computer and use it in GitHub Desktop.
Custom jsonb wrapper for Drizzle ORM when used with Postgresql
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 { SQL, sql } from 'drizzle-orm'; | |
/** | |
* Converts a raw object or array to a jsonb object for postgres | |
* | |
* @export | |
* @template T | |
* @param {(T | T[])} raw | |
* @return {*} {SQL<unknown>} | |
* | |
* Usage: | |
* ```typescript | |
* import { db } from '<your-drizzle-client>'; | |
* import * as schema from '<your-schemas>'; | |
* | |
* await db | |
.insert(schema.events) | |
.values({ | |
messageLogs: toJsonb([ | |
{ | |
message: "Some message", | |
createdAt: new Date().toISOString(), | |
} | |
]) | |
}) | |
* ``` | |
*/ | |
export function toJsonb<T>(raw: T | T[]): SQL<unknown> { | |
const convert = ( | |
value: undefined | null | string | number | bigint | boolean | object, | |
): string | null => { | |
if (value === undefined) return `""`; | |
if (value === null) return null; | |
if (typeof value === 'string') return `"${value}"`; | |
if ( | |
typeof value === 'number' || | |
typeof value === 'bigint' || | |
typeof value === 'boolean' | |
) { | |
return `${value}`; | |
} | |
if (Array.isArray(value)) { | |
return `[${value.map((t) => { | |
return convert(t); | |
})}]`; | |
} | |
if (typeof value === 'object') { | |
let objElements = ''; | |
Object.keys(value as object).forEach((i) => { | |
objElements += `"${i}": ${convert(value![i])},`; | |
}); | |
return `{${objElements.slice(0, -1)}}`; | |
} | |
throw new Error('Invalid data type for jsonb'); | |
}; | |
if (Array.isArray(raw)) { | |
return sql.raw(`'${convert(raw)}'::jsonb`); | |
} | |
if (typeof raw === 'object') { | |
return sql.raw(`'${convert(raw)}'::jsonb`); | |
} | |
throw new Error('Invalid data type for jsonb'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
should we take care of escaping here? like
"'"
to"''"