Skip to content

Instantly share code, notes, and snippets.

@stewartmcgown
Created September 15, 2021 13:03
Show Gist options
  • Save stewartmcgown/609eaffa8c2baa29165eb3c1578a03ee to your computer and use it in GitHub Desktop.
Save stewartmcgown/609eaffa8c2baa29165eb3c1578a03ee to your computer and use it in GitHub Desktop.
Class Transformer Class to BigQuery Schema
import { TableSchema } from '@google-cloud/bigquery';
import { TransformationType } from 'class-transformer';
import { defaultMetadataStorage } from 'class-transformer/cjs/storage';
import { MetadataStorage } from 'class-transformer/types/MetadataStorage';
import { Enum } from './autoenum';
import { ClassType } from './typeorm/class-type';
const meta: MetadataStorage = defaultMetadataStorage;
const BigQueryTypes = Enum(
'STRING',
'BYTES',
'INTEGER',
'FLOAT',
'BOOLEAN',
'TIMESTAMP',
'DATE',
'TIME',
'DATETIME',
'STRUCT',
);
export function classToBigQuerySchema<T>(clazz: ClassType<T>) {
const schema: (NonNullable<TableSchema['fields']>[0] & {
type: keyof typeof BigQueryTypes;
})[] = [];
// [
// {name: 'Name', type: 'STRING', mode: 'REQUIRED'},
// {name: 'Age', type: 'INTEGER'},
// {name: 'Weight', type: 'FLOAT'},
// {name: 'IsMagic', type: 'BOOLEAN'},
// ]
const props = meta.getExposedProperties(
clazz,
TransformationType.CLASS_TO_CLASS,
);
for (const prop of props) {
const type = Reflect.getOwnMetadata('design:type', clazz.prototype, prop);
schema.push({
name: prop,
type:
type === String
? 'STRING'
: type === Number
? 'FLOAT'
: type === Date
? 'DATETIME'
: type === Boolean
? 'BOOLEAN'
: type === BigInt
? 'INTEGER'
: 'STRING',
});
}
return schema;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment