Does anyone know how to get the string
representation of a type IType
in ydb-nodejs-sdk? Maybe there is some enum or method, but I don't find anything. Here's a simple example to show what I mean.
import { Session, TypedData, Types, Ydb, declareType, snakeToCamelCaseConversion, withTypeOptions } from "ydb-sdk";
export type TestModelType = {
id: string;
value: string;
};
@withTypeOptions({namesConversion: snakeToCamelCaseConversion})
export class TestModel extends TypedData implements TestModelType {
@declareType(Types.UTF8)
id: TestModelType['id']
@declareType(Types.UTF8)
value: TestModelType['value']
constructor(fields: TestModelType) {
super(fields);
this.id = fields.id;
this.value = fields.value;
}
}
export async function insertTest(session: Session, model: TestModel) {
const query = `
DECLARE $id AS ${doSomethingToGetFieldType(model.getType('id'))};
DECLARE $value AS ${doSomethingToGetFieldType(model.getType('value'))};
INSERT INTO \`tests\` (\`id\`, \`value\`)
VALUES ($id, $value);
`;
const preparedQuery = await session.prepareQuery(query);
await session.executeQuery(preparedQuery, {
'$id': model.getTypedValue('id'),
'$value': model.getTypedValue('value')
});
}
function doSomethingToGetFieldType(field: Ydb.IType): string {
// How to get the string representation of a type?
// ...
return '';
}
There isn't a built-in way to get the string representation directly from the Ydb.IType
interface. But, you can create a mapping of Ydb.IType
to their string representations.
YDB Node.js SDK
comes with the Type
class, which contains various static properties representing different types of YDB
. Each of these property is an instance of a particular class or subclass of Type
. You can create a map
where keys
are the class names of these types and the values are their string representation:
const Types = Ydb.Types;
function getYDBType(type: Ydb.IType): string {
if (type === Types.Bool) {
return 'Bool';
}
if (type === Types.Uint8) {
return 'Uint8';
}
if (type === Types.Uint32) {
return 'Uint32';
}
if (type === Types.Uint64) {
return 'Uint64';
}
if (type === Types.Int8) {
return 'Int8';
}
if (type === Types.Int32) {
return 'Int32';
}
if (type === Types.Int64) {
return 'Int64';
}
if (type === Types.Float) {
return 'Float';
}
if (type === Types.Double) {
return 'Double';
}
if (type === Types.UTF8) {
return 'Utf8';
}
if (type === Types.JSON) {
return 'Json';
}
if (type === Types.UUID) {
return 'Uuid';
}
//... add other types as per requirements
throw new Error('Unsupported YDB type ' + type);
}
function doSomethingToGetFieldType(field: Ydb.IType): string {
return getYDBType(field);
}
It's kinda manual to do this, but if you don't have so many types and don't want to check it all the time it shouldn't be a problem