objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

Add support for Buffer ids in typescript typings

Open kellnerd opened this issue 3 years ago • 0 comments

Similar to #1936. It is also possible (and even necessary e.g. in MySQL) to use a binary id column for an UUID which can be represented as a Buffer in the TS model.

class Person extends Model {
	id: Buffer;
	static tableName = 'Person';
}
// ... init and bind knex ...
const person = Person.query().findById(knex.fn.uuidToBin('a5f436e3-452a-443e-b226-30107e5f4b0c'));
select `Person`.* from `Person` where `Person`.`id` = X'443e452aa5f436e3b22630107e5f4b0c'

The above code works and builds a valid query for MySQL, but TS shows me a type error until I enhance the type definitions: https://github.com/Vincit/objection.js/blob/8f8896584281c87773fab33025061cddab2ebc3f/typings/objection/index.d.ts#L139

 type Id = string | number | BigInt | Buffer;

P.S. Originally I had hoped to hide the binary UUID at database level and use $parseDatabaseJson() and $formatDatabaseJson() to convert it into a string property of my model. This works but isn't really worth the effort, since I have to manually convert all UUID strings to Buffer before I can use them for find queries nevertheless. These two methods only affect the inserted and returned pojos, right? Or is there a better way to handle this which I have missed so far?

kellnerd avatar Apr 17 '22 11:04 kellnerd