Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat custom typecast #38

Merged
merged 7 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions __tests__/decode.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { Field } from '../src'
import { ColumnType, Decoders } from '../src/config'
import { cast } from '../src/decode'

describe('decode', () => {
describe('cast', () => {
test('use default decode method if config not provided', () => {
expect(cast(makeField(ColumnType.BIGINT), '21412421321421521321', {})).toEqual('21412421321421521321')
expect(cast(makeField(ColumnType.FLOAT), '1.2', {})).toEqual(1.2)
expect(cast(makeField(ColumnType.INT), '1', {})).toEqual(1)
})

test('override default decode method if config provided', () => {
const config: Decoders = {
[ColumnType.BIGINT]: BigInt,
[ColumnType.FLOAT]: String
}

expect(cast(makeField(ColumnType.BIGINT), '21412421321421521321', config)).toEqual(21412421321421521321n)
expect(cast(makeField(ColumnType.FLOAT), '1.2', config)).toEqual('1.2')
expect(cast(makeField(ColumnType.INT), '1', config)).toEqual(1)
})
})
})

function makeField(type: ColumnType): Field {
return {
name: 'foo',
type: type,
nullable: false
}
}
40 changes: 40 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,55 @@ export interface Config {
fetch?: (input: string, init?: Req) => Promise<Res>
arrayMode?: boolean
fullResult?: boolean
decoders?: Decoders
}

export interface ExecuteOptions {
arrayMode?: boolean
fullResult?: boolean
decoders?: Decoders
}

export interface TxOptions {
isolation?: 'READ COMMITTED' | 'REPEATABLE READ'
}

export type ExecuteArgs = object | any[] | null

export const enum ColumnType {
TINYINT = 'TINYINT',
UNSIGNED_TINYINT = 'UNSIGNED TINYINT',
SMALLINT = 'SMALLINT',
UNSIGNED_SMALLINT = 'UNSIGNED SMALLINT',
MEDIUMINT = 'MEDIUMINT',
INT = 'INT',
UNSIGNED_INT = 'UNSIGNED INT',
YEAR = 'YEAR',
FLOAT = 'FLOAT',
DOUBLE = 'DOUBLE',
BIGINT = 'BIGINT',
UNSIGNED_BIGINT = 'UNSIGNED BIGINT',
DECIMAL = 'DECIMAL',
CHAR = 'CHAR',
VARCHAR = 'VARCHAR',
BINARY = 'BINARY',
VARBINARY = 'VARBINARY',
TINYTEXT = 'TINYTEXT',
TEXT = 'TEXT',
MEDIUMTEXT = 'MEDIUMTEXT',
LONGTEXT = 'LONGTEXT',
TINYBLOB = 'TINYBLOB',
BLOB = 'BLOB',
MEDIUMBLOB = 'MEDIUMBLOB',
LONGBLOB = 'LONGBLOB',
DATE = 'DATE',
TIME = 'TIME',
DATETIME = 'DATETIME',
TIMESTAMP = 'TIMESTAMP',
BIT = 'BIT',
JSON = 'JSON'
}

export type Decoders = {
[P in ColumnType]?: (rawValue: string) => any
}
8 changes: 7 additions & 1 deletion src/decode.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { Decoders } from './config'
import { Field } from './index.js'

export function cast(field: Field, value: string | null): any {
export function cast(field: Field, value: string | null, decoder: Decoders): any {
if (value === null) {
return null
}

// use user provided decoder if exists
if (decoder[field.type]) {
return decoder[field.type](value)
}

switch (field.type) {
// bool will be converted to TINYINT
case 'TINYINT':
Expand Down
17 changes: 9 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { format } from './format.js'
import { cast } from './decode.js'
import { DatabaseError } from './error.js'
import { Config, ExecuteOptions, ExecuteArgs, TxOptions } from './config.js'
import { Config, ExecuteOptions, ExecuteArgs, TxOptions, Decoders } from './config.js'
import { postQuery } from './serverless.js'

export { Config, ExecuteOptions, ExecuteArgs, DatabaseError }
Expand Down Expand Up @@ -120,9 +120,10 @@ export class Connection {

const arrayMode = options.arrayMode ?? this.config.arrayMode ?? false
const fullResult = options.fullResult ?? this.config.arrayMode ?? false
const decoders = { ...this.config.decoders, ...options.decoders }

const fields = resp?.types ?? []
const rows = resp ? parse(fields, resp?.rows ?? [], cast, arrayMode) : []
const rows = resp ? parse(fields, resp?.rows ?? [], cast, arrayMode, decoders) : []

if (fullResult) {
const rowsAffected = resp?.rowsAffected ?? 0
Expand All @@ -147,19 +148,19 @@ export function connect(config: Config): Connection {
}

type Cast = typeof cast
function parseArrayRow(fields: Field[], rawRow: string[], cast: Cast): Row {
function parseArrayRow(fields: Field[], rawRow: string[], cast: Cast, decoders: Decoders): Row {
return fields.map((field, ix) => {
return cast(field, rawRow[ix])
return cast(field, rawRow[ix], decoders)
})
}

function parseObjectRow(fields: Field[], rawRow: string[], cast: Cast): Row {
function parseObjectRow(fields: Field[], rawRow: string[], cast: Cast, decoders: Decoders): Row {
return fields.reduce((acc, field, ix) => {
acc[field.name] = cast(field, rawRow[ix])
acc[field.name] = cast(field, rawRow[ix], decoders)
return acc
}, {} as Row)
}

function parse(fields: Field[], rows: string[][], cast: Cast, arrayMode: boolean): Row[] {
return rows.map((row) => (arrayMode === true ? parseArrayRow(fields, row, cast) : parseObjectRow(fields, row, cast)))
function parse(fields: Field[], rows: string[][], cast: Cast, arrayMode: boolean, decode: Decoders): Row[] {
return rows.map((row) => (arrayMode === true ? parseArrayRow(fields, row, cast, decode) : parseObjectRow(fields, row, cast, decode)))
}
Loading