How can I incorporate static content files bundled with my JSON object into the API response in Nest.js?

Within my Nest.js API, there is a GET endpoint that needs to retrieve a database row along with up to 6 image files (base64 encoded) in the response.

Currently, I am achieving this by extracting unique file names stored in 6 columns of the database and then using the @Res decorator to send one of the images back like so:

@Get('/findVehicleEntry/:id')
async findVehicleEntry(@Param('id') id: number, @Res() res) {
    const resVehicle: Vehicle = await this.vehiclesService.findVehicleEntry(id);
    if (resVehicle) {
        res.sendFile(resVehicle.photo1, { root: 'image-uploads' });
    }
}

However, my goal is to fetch each image from the folder, convert it to base64, assign it to the corresponding property in `resVehicle`, and eventually send all 6 images together in the response payload.

I envision the process to be something like this:

@Get('/findVehicleEntry/:id')
async findVehicleEntry(@Param('id') id: number, @Res() res) {
    const resVehicle: Vehicle = await this.vehiclesService.findVehicleEntry(id);
    if (resVehicle) {
        let image = something.get('resVehicle.photo1', 'my/path/to/image-uploads');
        image = Buffer.from(image).toString('base64');
        resVehicle.photo1 = image;
        // Repeat for remaining 5 images
        res.send(resVehicle);
    }
}

This project marks my introduction to Nest/Express/Node development, and being new to APIs, guidance on best practices or better approaches would be greatly appreciated. Thank you!

Edit: Recent learnings have highlighted concerns around encoding large files in base64. While willing to abandon this idea, I am still seeking advice on effectively returning both the JSON object from the database and the 6 associated images within the same response structure.

Answer №1

Using base64 encoding for images is not recommended.

The common approach in this situation is: Rather than embedding the images directly, provide the image path in your JSON response and allow the API consumer to access the image using the path.

  • Store the image files in a publicly accessible directory, instead of in a database. This way, they can be accessed by the browser at a URL like
    yourdomain.com/images/image232.jpg
  • In your database, save the paths to these images as strings (
    image1: "yourdomain.com/images/image232.jpg"
    )
  • Include the image path in your JSON response (
    {make:"Toyota", image1:"yourdomain.com/images/image232.jpg"}
    )
  • The end user consuming your API will then utilize the path to retrieve the image.

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

Utilize React to display a Selected button within a whitespace

Currently, I am encountering an issue in React where I have a group of buttons at the bottom. Upon selecting a button, the corresponding text should display at the top within a specified whitespace. However, I am looking to have the whitespace already occu ...

Error TS7053 occurs when an element is given an 'any' type because a 'string' expression is being used to index an 'Object' type

When attempting to post data directly using templateDrivenForm and retrieve data from Firebase, I encountered the following type error message. Here are the relevant parts of my code: // Posting data directly using submitButton from templateDrivenForm onC ...

After mapping in JavaScript, delete the property name

Is there a way to exclude the property name from the returned value? I want to eliminate the property name "projects: [ ]" from the output. router.get("/", (req, res, next) => { Project.find() .exec() .then(docs => { res.status(200) ...

Minimize property names with Webpack

Our Vue 2.x.x application, written in typescript, needs to be structured into modules such as /users, /articles, /reports, following a micro frontend architecture. We are looking for a solution that allows us to load these modules dynamically based on use ...

Ways to showcase the refined object array upon clicking a button in Angular

I have been working on a project to create a task management system. The project consists of two main components: itemList and item. The itemList component takes input values for tasks and displays them in the item component. https://i.sstatic.net/SaRNMm. ...

Customizing key values within nested objects in Angular2: A comprehensive guide

I need assistance with setting up a JSON object for a post in Angular2/Typescript. I am trying to dynamically set the nested object values for a key. Is it possible to achieve this using Angular2/Typescript? I have attempted to retrieve the values from JS ...

Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema: model Directory { id String @id @default(cuid()) name String? parentDirectoryId String? userId String parentDirectory Directory? @relation("p ...

The 'payload' property is not found within the 'Actions' type

I recently started using TypeScript and Visual Studio Code. I encountered the following issue: *[ts] Property 'payload' does not exist on type 'Actions'. This is my code: action.ts file: import { Action } from '@ngrx/store&apos ...

Using NestJS to inject a Factory provider into another Factory

I've gone through various questions here, but none of them addressed my issue: NestJS - Inject factory provider into another provider doesn't work I'm trying to set up an async provider that retrieves configurations from a remote repositor ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

Error: JSON parsing error at position 0, caused by an unexpected token "<", originating from devtools shell.js

I am in the process of developing a desktop application using Electron.js and Express.js Upon initial loading, I encountered a warning that stated: SyntaxError: Unexpected token < in JSON at position 0", source: devtools://devtools/bundled/shell.j ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

How to Switch to a Different Tab in a NativeScript TabView

I'm struggling to figure out how to programmatically navigate to a different tab within a tabView from a partial View. Each tab is located in a child folder with its own html, ts, js, and css files. In this scenario, when a user clicks on an item in a ...

Building intricate structures in Typescript: A comprehensive guide

My objective is to create a sophisticated object, with values that need to be calculated or extracted from another object. The specific object I am working on is defined as follows: interface A extends B { key1: string key2: { it's a complex object ...

Unable to deliver static HTML file using Express/Node

Currently, I am using Express in conjunction with Node to develop a React application that is a single page, with the exception of one static HTML file. While everything is functioning properly locally, I encounter issues when trying to access localhost:3 ...

Ways to relay information from the server to the client in a MEAN stack setup?

I'm a beginner with the MEAN stack app and encountering difficulties in sending data from the server to the front end. Currently, I can establish some communication between them, but that's about it. In the server, I have set up the JSON message ...

"Error Popping Up: Duplicate Identifier Detected in Popper.js

I've hit a roadblock trying to resolve this error or identify its root cause. Despite no changes in the code, I suspect it may be due to an updated NPM package. The error log displayed in the console is specific to an Angular2 application. ERROR in [ ...

Expanding TypeScript Definitions

I've been experimenting with TypeScript and Express. After importing type declarations from Typings, I found the following code: // Imported from typings // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f2 ...

Compel a customer to invoke a particular function

Is there a way to ensure that the build method is always called by the client at the end of the command chain? const foo = new Foo(); foo.bar().a() // I need to guarantee that the `build` method is invoked. Check out the following code snippet: interface ...

Issue with NullInjectorError: Failure to provide a custom component - Attempting to add to providers without success

I keep encountering errors during my test attempts... Despite looking into similar issues, I am still facing problems even after adding my custom LoginComponent to app.module.ts providers. It is already included in the imports section. app.module.ts @Ng ...