How to save buffer of data into postgres database using prisma ORM

Viewed 29

I am trying to save a buffer of data (image file) sent from client to a postgress db. In the database the data are stored as Oid and i do not know how to save a buffer of data as Oid.

Here is what prisma generated seeing my db table:

model image {
  id         String   @id @db.Uuid @default(uuid())
  data       Int      @db.Oid
  image_size BigInt
  image_type String?  @db.VarChar(25)
  name       String?  @db.VarChar(30)
  client     client[]
}

and here is my server side code to handel post request:

app.post ("/img", async (req: Request | any, res: Response) => {
    const data = req.files.data;
    const img = await prisma.image.create({
        data: {
            name: data.name,
            image_type: data.mimetype,
            image_size: data.size,
            data: data.data
        },
    });
    res.send({
        "status": "working on the data",
        "data": img
    });
});

I am using express-fileupload to extract file data from request and body-parser to parse the incoming http request

and the output I am getting is:

[ERROR] 13:29:22 Error:
Invalid `prisma.image.create()` invocation in
D:\programs\projects\TwitterClone\Api\src\app.ts:24:36

  21
  22 app.post ("/img", async (req: Request | any, res: Response) => {
  23     const data = req.files.data;
→ 24     const img = await prisma.image.create({
           data: {
             name: 'vasu.jpg',
             image_type: 'image/jpeg',
             image_size: 9784,
             data: Buffer(3)
             ~~~~~~~~~~~
           }
         })

Argument data: Got invalid value Buffer(3) on prisma.createOneimage. Provided Bytes, expected Int.
1 Answers

oid is an internal type of Postgres: https://www.postgresql.org/docs/14/datatype-oid.html

You cannot store binary data in it. Potentially, the large objects of postgres are used to store the images: https://www.postgresql.org/docs/current/largeobjects.html

That's currently not supported by Prisma.

I see two options for you:

  1. If my assumption is right and you want to use large objects, you could use SQL directly (https://www.postgresql.org/docs/current/lo-interfaces.html) but miss the features of prisma.

  2. If you want to use prisma, you could change your database schema to bytea which is supported by Prisma: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#bytes

Related