aboutsummaryrefslogtreecommitdiffstats
path: root/packages/pipeline/src/utils/transformers/number_to_bigint.ts
blob: 85560c1f0d2464c304ffca6e88c7e8be94f54f79 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { BigNumber } from '@0x/utils';
import { ValueTransformer } from 'typeorm/decorator/options/ValueTransformer';

const decimalRadix = 10;

// Can be used to convert a JavaScript number type to a Postgres bigint type and
// vice versa. By default TypeORM will silently convert number types to string
// if the corresponding Postgres type is bigint. See
// https://github.com/typeorm/typeorm/issues/2400 for more information.
export class NumberToBigIntTransformer implements ValueTransformer {
    // tslint:disable-next-line:prefer-function-over-method
    public to(value: number): string {
        return value.toString();
    }

    // tslint:disable-next-line:prefer-function-over-method
    public from(value: string): number {
        if (new BigNumber(value).greaterThan(Number.MAX_SAFE_INTEGER)) {
            throw new Error(
                `Attempted to convert PostgreSQL bigint value (${value}) to JavaScript number type but it is too big to safely convert`,
            );
        }
        return Number.parseInt(value, decimalRadix);
    }
}

export const numberToBigIntTransformer = new NumberToBigIntTransformer();