My backend is built using NestJS and Prisma for the database. Within my attachments model, I store the file locations. Currently, I save the files with the full URL needed to retrieve them like this
'http://127.0.0.1:5000/api/123.jpg'
. However, I would like to save it as '/123.jpg'
and have Prisma automatically add the domain string http://127.0.0.1:5000/api
in front so that the server can easily be moved to different domains.
Currently, I'm using a loop to manually add the domain to each query result, but I was wondering if there's a more efficient way for Prisma to handle this during the query execution process?
Here is a snippet of my schema.prisma file:
model Attachment {
id Int @id @default(autoincrement())
//Is there a way to automatically prepend a domain URL to the string before sending it out?
thumbnail String?
original String?
}
Solution
I implemented @ConnorFogarty's answer into /prisma/prisma.ts as shown below:
import { PrismaClient } from '@prisma/client';
import { APP_URL } from '../src/common/constants';
let prisma: PrismaClient;
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient();
} else {
if (!global.prisma) {
global.prisma = new PrismaClient();
}
prisma = global.prisma;
}
//Middleware to prepend server link to all requests for Attachments with original/thumbnail
prisma.$use(async (params, next) => {
console.log('params', params)
if (params.model == 'Attachment' && params.action == 'findMany') {
params.args.data.thumbnail = APP_URL + params.args.data.thumbnail;
}
return next(params)
})
export default prisma;
In my console output, you can see that params are missing params.args.data:
params {
args: { include: { avatar: true, addresses: true } },
dataPath: [],
runInTransaction: false,
action: 'findMany',
model: 'User'
}