Last active
January 26, 2022 10:37
-
-
Save evenfrost/32d450f2f1b49e3a3e2dbfe68c6facc5 to your computer and use it in GitHub Desktop.
Custom MikroORM type for Postgres 'jsonb[]'
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 { Type, ValidationError } from '@mikro-orm/core'; | |
export default class JsonArrayType extends Type<Record<string, any>[], string> { | |
convertToDatabaseValue(value: Record<string, any>[]): string { | |
if (!Array.isArray(value)) { | |
throw ValidationError.invalidType(JsonArrayType, value, 'JS'); | |
} | |
const resultValue = JSON.stringify(value) | |
.replace(/"/g, '\\"') | |
.replace(/({.*?})/g, '"$&"') | |
.replace(/^\[/, '{') | |
.replace(/\]$/, '}'); | |
return resultValue; | |
} | |
convertToJSValue(value: Record<string, any>[] | string): Record<string, any>[] { | |
if (typeof value !== 'string') { | |
return value; | |
} | |
const preparedValue = value | |
.replace(/^\{/, '[') | |
.replace(/\}$/, ']') | |
.replace(/"({.*?})"/g, '$&') | |
.replace(/\\\\"/, '"'); | |
return JSON.parse(preparedValue) as Record<string, any>[]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment