Last active
September 15, 2021 15:04
-
-
Save DiegoVictor/9aa2169e31c632f6d6972b244e85ecf7 to your computer and use it in GitHub Desktop.
Save binary field with typeorm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require("reflect-metadata"); | |
const { | |
EntitySchema, | |
createConnection, | |
Table, | |
getConnection, | |
} = require("typeorm"); | |
const { randomUUID } = require("crypto"); | |
const Tag = new EntitySchema({ | |
name: "tags", | |
columns: { | |
id: { | |
type: Number, | |
primary: true, | |
}, | |
serial: { | |
type: Buffer, | |
}, | |
}, | |
}); | |
const config = { | |
type: "sqlite", | |
database: "./database.sqlite", | |
entities: [Tag], | |
}; | |
const serial = randomUUID(); | |
console.log(`Generated uuid: ${serial}`); | |
createConnection(config) | |
.then((conn) => | |
// create table "tags" if not exists | |
conn.createQueryRunner().createTable( | |
new Table({ | |
name: "tags", | |
columns: [ | |
{ | |
name: "id", | |
type: "int", | |
isPrimary: true, | |
}, | |
{ | |
name: "serial", | |
type: "binary(16)", | |
}, | |
], | |
}), | |
true | |
) | |
) | |
.then(() => | |
// Save tag | |
getConnection() | |
.getRepository(Tag) | |
.save({ | |
id: Date.now(), | |
serial: Buffer.from(serial.replace(/-/gi, ""), "hex"), // parse to buffer before save | |
}) | |
) | |
.then((saved) => { | |
console.log("saved tag", saved); | |
return saved; | |
}) | |
// Retrieve the saved tag by id | |
.then((saved) => getConnection().getRepository(Tag).findOne(saved.id)) | |
.then((tag) => { | |
console.log("retrieved tag", { | |
id: tag.id, | |
serial: Buffer.from(tag.serial, "binary") | |
.toString("hex") // convert to hexadecimal string | |
.split("") | |
.reduce( | |
(filled, char) => filled.replace(/x/i, char), | |
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" | |
), | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment