Created
March 17, 2024 13:48
-
-
Save flleeppyy/220f0184c1c1d3413850e6d0c4386ad8 to your computer and use it in GitHub Desktop.
Knex JSON parser to/from SQLite
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
function parseToDatabaseJson<T>(obj: Record<string, unknown>): T; | |
function parseToDatabaseJson<T>(obj: Record<string, unknown>): string | T | Record<string, unknown> { | |
if (obj._tableName) delete obj._tableName; | |
if (Object.prototype.toString.call(obj) === "[object Array]") { | |
return JSON.stringify(obj); | |
} else if (typeof obj === "object") { | |
const newObj: Record<string, unknown> = {}; | |
for (const key in obj) { | |
// eslint-disable-next-line @typescript-eslint/naming-convention | |
const type_ = Object.prototype.toString.call(obj[key]); | |
if (["[object Array]", "[object Object]"].includes(type_)) { | |
newObj[key] = JSON.stringify(obj[key]); | |
continue; | |
} | |
newObj[key] = obj[key]; | |
} | |
return newObj; | |
} else { | |
return obj; | |
} | |
} | |
function parseFromDatabaseJson<T>(obj: T): T { | |
if (typeof obj === "string") { | |
try { | |
if (Number.parseInt(obj)) { | |
return obj; | |
} | |
obj = JSON.parse(obj) || obj; | |
} catch { | |
return obj; | |
} | |
} | |
if ((obj === undefined || obj === null) && obj !== false) { | |
// eslint-disable-next-line unicorn/no-null | |
return null as typeof obj; | |
} | |
if (Array.isArray(obj)) { | |
return obj.map((item) => { | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | |
return parseFromDatabaseJson(item); | |
}) as T; | |
} else if (typeof obj === "object") { | |
const newObj: Record<string, unknown> = {}; | |
for (const key in obj) { | |
newObj[key] = parseFromDatabaseJson(obj[key]); | |
} | |
return newObj as T; | |
} else { | |
return obj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment