sql: Add NULL support to database wrappers
This commit is contained in:
+1
-1
@@ -3,7 +3,7 @@ import * as sql from "sql-bricks-postgres";
|
||||
import { Id } from "../model";
|
||||
|
||||
export interface Row {
|
||||
[key: string]: string;
|
||||
[key: string]: string | null;
|
||||
}
|
||||
|
||||
export interface Transaction {
|
||||
|
||||
+21
-7
@@ -3,15 +3,23 @@ import snakeCase from "snake-case";
|
||||
import { Row } from "./api";
|
||||
|
||||
interface ColMapper<F> {
|
||||
_read(str: string): F;
|
||||
_read(str: string | null): F;
|
||||
|
||||
_write(val: F): string;
|
||||
_write(val: F): string | null;
|
||||
}
|
||||
|
||||
type Spec<R> = {
|
||||
[K in keyof R]: ColMapper<R[K]>;
|
||||
};
|
||||
|
||||
function _nn(str: string | null): string {
|
||||
if (str === null) {
|
||||
throw new Error("Unexpected NULL returned from database");
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function objects describing the precise way in which our SQL driver
|
||||
* transmits and receives values to the database as strings. Note that we could
|
||||
@@ -20,25 +28,31 @@ type Spec<R> = {
|
||||
*/
|
||||
export const T = {
|
||||
bigint: {
|
||||
_read: (str: string) => BigInt(str),
|
||||
_read: (str: string) => BigInt(_nn(str)),
|
||||
_write: (val: bigint) => val.toString(),
|
||||
},
|
||||
boolean: {
|
||||
_read: (str: string) => str === "true",
|
||||
_read: (str: string) => _nn(str) === "true",
|
||||
_write: (val: boolean) => val.toString(),
|
||||
},
|
||||
number: {
|
||||
_read: (str: string) => parseInt(str),
|
||||
_read: (str: string) => parseInt(_nn(str)),
|
||||
_write: (val: number) => val.toString(),
|
||||
},
|
||||
string: {
|
||||
_read: (str: string) => str,
|
||||
_read: (str: string) => _nn(str),
|
||||
_write: (val: string) => val,
|
||||
},
|
||||
Date: {
|
||||
_read: (str: string) => new Date(str),
|
||||
_read: (str: string) => new Date(_nn(str)),
|
||||
_write: (val: Date) => val.toISOString(),
|
||||
},
|
||||
nullable: <F>(inner: ColMapper<F>) => ({
|
||||
_read: (str: string | null) =>
|
||||
str !== null ? inner._read(str) : undefined,
|
||||
_write: (val: F | undefined) =>
|
||||
val !== undefined ? inner._write(val) : null,
|
||||
}),
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user