This is my images
table in PostgreSQL:
CREATE TABLE IF NOT EXISTS images (
----------------------------------------------------
id UUID NOT NULL DEFAULT uuid_generate_v4(),
----------------------------------------------------
pic BYTEA NOT NULL,
ext VARCHAR(10) NOT NULL,
----------------------------------------------------
CONSTRAINT images_pk
PRIMARY KEY (id)
----------------------------------------------------
);
-- Inserting Fake Data
SELECT set_config(
'default_pic_path',
'/path/to/image.png',
FALSE
);
INSERT INTO
mi.images (
pic,
ext
)
VALUES
------------------------------
(
bytea('default_pic_path'),
'png'
);
------------------------------
And I would like to have an endpoint for adding images to the DB and also another for retrieving them, sending them back with the proper image extension (e.g. .png
, .jpg
, etc.).
What is the recommended way of doing this in ExpressJS with node-pg
?
So far, I've found tons of ways of doing this converting images to text, but that's highly inefficient... I've also found some solutions in which we turn the returned node-pg
Buffer
into a local file and then use res.sendFile(...)
, but that is also highly inefficient. Is there a better way?
Anyways, here's a sketch of an endpoint for getting an image (in TypeScript), with the local creation of a file I had criticized:
import { Request, Response } from "express";
export async function getImage(req: Request, res: Response) {
try {
const mainPool = new Pool({
user: "postgres",
password: "password",
database: "main",
host: "localhost",
port: 5432,
});
const results = await mainPool.query(/* sql */ `
SELECT pic, ext
FROM images
`);
const pic = results.rows.[0].pic as Buffer;
const extension = results.rows.[0].ext as string;
const filename = `default_pic.${extension}`;
const filepath = join(
__dirname,
"../path/to/assets/folder/",
`assets/${filename}`
);
// Doesn't really write the file properly,
// probably some error with encoding...
writeFileSync(filepath, pic);
res.sendFile(filepath);
} catch (e) {
console.log(e);
}
}