What is the best way to prepend a string to a query result in Prisma?

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'
}

Answer №1

Prisma middleware allows you to execute code before or after a query. Specifically, you have the ability to create a middleware function for the findMany operation (or any other queries) that adds the server URL in front of the attachment path:

const prisma = new PrismaClient();

prisma.$use(async (params, next) => {
    const server = "http://127.0.0.1:5000/api/";

    if (params.model === "Attachment" && params.action === "findMany") {
      // Execute findMany query
      const result = await next(params);

      // Add server URL to thumbnail
      const modified = result.map((res) => ({
        ...res,
        thumbnail: server + res.thumbnail,
      }));

      return modified;
    }

    return next(params);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for obtaining the identifier of a div element while employing the bind() function in jQuery

Imagine having the following div. <div id="456" class="xyz">Lorem Ipsum</div> If I want to execute a function when this specific div is hovered over, I can achieve it like this: $(".xyz").bind({ mouseenter : AnotherFunction(id) }); Prio ...

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

How can JavaScript help determine the performance of a device's CPU and GPU?

(Let's consider this question in the context of web development) Recently, I've been working on developing a web app interface using three.js and implementing a fallback option between WebGL and Canvas renderer for desktop browsers. However, I& ...

Enhance the appearance of the jQuery document.ready function

I'm attempting to customize the jQuery document.ready function <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript> $(function() { c ...

Utilize ReactJS to apply emphasis to specific text phrases

I am having difficulty highlighting text that matches the query because I cannot figure out how to display tags as HTML instead of text. var Component = React.createClass({ _highlightQuery: function(name, query) { var regex = new RegExp("(" + ...

What is the best way to group items using jQuery?

Below is the HTML markup I am working with: <article class="linkWrapper" data-group="1"> <a href="#">...</a> </article> <article class="linkWrapper" data-group="1"> <a href="#">...</a> </article> <a ...

Having trouble running the server in Node.js

When working with Node.Js, I encountered a specific issue My progress stopped at 6:16 when the instructions mentioned running "node server.js" to open 127.0.0.1:3000, but instead, an error occurred. https://i.sstatic.net/6esE5.png Upon checking my brows ...

Fill the concealed field with the auto-complete suggestion

My HTML form includes a regular text input as well as a hidden field. The code below will update the value of the hidden field with the content from the text field whenever it is modified or if the text field has a default value: $(document).ready(func ...

Is it possible to extract the exif data from an image upon uploading it with Javascript?

I am working with an input file type: <input type='file' id='upload_files' name='upload_files' file-model='upload_files'/> Is it possible to extract exif data from the uploaded image using only javascript/ang ...

Dynamic stylesheet in Vue component

Currently, I am utilizing a Vue component (cli .vue) and facing the challenge of selectively displaying my stylesheet based on a boolean value. To put it simply: When myVar==false, the component should not load its styles. <style v-if="myVar" lang="sc ...

Exploring nested checkboxes in ReactJS using mapping techniques

I have a function that triggers child checkboxes once the main checkbox is checked, and all these checkboxes are mapped from JSON data. The main checkboxes (highest level) and all of their children checkboxes (2nd level) underneath them are shown on click ...

The property 'map' cannot be read as it is undefined when outside the scope of page.evaluate()

Here is a code snippet to consider: let foo = await page.evaluate( () => { let bar = [...document.querySelectorAll(".foobar")]; return bar.map((u) => u.textContent.trim()); } ); foo.forEach((u) => { console.log(u); }); Now let's ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

Javascript- Retrieving information from an array containing various objects

Struggling with extracting data from another object. The information provided is not in English, but that shouldn't be an issue. [ { productName: 'Data Sharer', itemNumber: 'TESZOR 61.20.42', unit: 'month', ...

What is the best way to provide Monaco editor's loader.js and its dependencies on a local server for my React project?

Currently, I have integrated Monaco Editor in my project by utilizing the npm package Monaco Editor. When I build and serve my code on localhost, I noticed that the Loader Script is being loaded from a Content Delivery Network (CDN). I am curious to know ...

How come my div containers are intersecting each other exactly at the center with a height of 50% and width of 50%?

I am facing an issue where the four boxes I created are overlapping, despite being set to a height of 50vh and a width of 50vw. How can I resolve this problem and prevent them from overlapping? https://i.sstatic.net/yRXv1.png https://i.sstatic.net/4hra6. ...

React and Django integration issues: CSRF Token missing in production environment, posing a challenge specifically for the create method

During development, the csrf cookie used to be set normally if it was not available in the application tab in the dev tool. However, on production, every time I try to create a new post, I get an error saying " CSRF Failed: CSRF token from the 'X-Csrf ...

Will other functions in the file run if only a single function is imported?

The file bmiCalculator.ts contains the following code: import { isNotNumber } from './utils'; export default function calculateBmi(height: number, weight: number) { const bmi = weight / Math.pow(height / 100, 2); if (bmi < 18.5) { re ...

What could be causing the unexpected behavior of TypeScript in Visual Studio Code?

VSCode is showing errors, but everything is functioning properly. Here are some of the errors: Type expected. [ { "resource": "/C:/Users/Dell/Desktop/vite-project/src/App.tsx", "owner": "typescript", "code": "1110", "se ...

Leverage the key-value pairs in JSON to automatically suggest types within the function parameters

If we have data structured like this: { "key1": "hardcoded string", "key2": "another hardcoded string", } Imagine a function with 2 parameters where the first parameter should refer to key1 and the second to i ...