Guide to organizing code for a REST API using Express.js

Recently, I have been working on developing a REST API using Sails.js. As I outlined the resources needed for my application, it struck me that many frameworks (based on Express) are proficient at handling single resources.

However, in most cases, I found myself needing to manage multiple resources simultaneously. To illustrate, consider the following structure and relationships between resources:

Users -- user's metadata
      `- Books -- book metadata
               `- author

      `- Gallery -- Images -- image metadata
                 `- Videos -- video metadata

The resources mentioned above include: Users, Books, Gallery, Images, and Videos. Each resource only stores the IDs of its subresources. The challenge arose when inserting a new subresource. For example, after adding a book, I had to identify its owner and establish a reference to this book.

Things got more complex when uploading an image. Following the creation of an Image, knowing the user who uploaded it, I needed to create a gallery, add the image reference to the gallery, and link the gallery's ID to that user.

This process required coordination between controllers for users, images, galleries, leading to code redundancy and complexity (such as making Users model calls from Images or Gallery controllers).

An immediate fix could involve eliminating the Gallery subResource and directly associating videos and photos with the user, but this is just one approach.

Therefore, I aim to organize my app by establishing distinct modules for Users, Galleries, etc., each providing a basic CRUD API. Then, route incoming requests to the relevant controller/handler to interact with these modules seamlessly. Additionally, for single-resource requests, automatically redirecting to the module's handler would be ideal.

Would this structuring pattern benefit scaling a REST API (despite being more about data manipulation than adhering strictly to REST principles)?

If so, are there any libraries or perhaps extensions to Express that can help create these modules? I am currently utilizing mongoDB with mongooseJS for models.

Could you recommend a suitable file structure for the application?

Adding the tag golang because I am exploring whether there are frameworks like beego, martini, or goweb that align with my requirements.

This inquiry is not aimed at soliciting opinions but seeks insights from someone experienced with similar challenges. Despite searching extensively, I have struggled to find solutions beyond basic REST API tutorials employing unspecified frameworks, which fail to address the architecture/scalability concerns essential for deploying a robust application.

Thank you.

Answer №1

As someone who is also new to sails.js, it appears that you are seeking information on associative models.

While not fully implemented yet, these can still be utilized with sails v0.10.0

I anticipate that associations will be fully integrated by the time your project is prepared for deployment.

You can find more details here: https://example.com/sails/issues/456

This means structuring relationships like this:

  • Article belongsTo Category 5

  • Image belongsTo Article 12

  • Category hasMany Article and hasMany Image

These declarations are conceptual and do not require literal coding - just a helpful way to conceptualize the relationships.

Best of luck with your project! :)

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

Express routes are causing conflicts with React routes

I currently have the build files for my react application (generated from running npm run build) stored in the /public folder within my backend directory. Here is the content of my index.js file located in my backend: const express = require('express ...

Nodejs application crashes due to buffer creation issues

router.post('/image', multipartMiddleware , function(req, res) { var file_name = req.body.name; var data = req.body.data; var stream = fs.createReadStream(data); //issue arises here return s3fsImpl.writeFile(file_name , stream).t ...

Outdated errors encountered during the installation of packages in Gatsby

Encountering errors while installing packages with a Gatsby theme. I have already attempted npm install --legacy-peer-deps without success. Even after running gatsby develop , the errors persist: Here is the list of errors I am encountering: npm ERR! cod ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...

The event handlers on all elements are not loaded when the HTML page is rendered

Currently in the process of developing a project which involves a web server app built with nodejs + express and some client views that are rendered using ejs. In the main app.js file, the following code is present: const express = require('express& ...

What is the best method for tracking the execution time of functions in Node.js?

My nodejs application has numerous functions that need to be executed. I am looking for a way to log the time taken to execute each function. For example, when my app runs these functions: execfn1(); -> should output in some log, takes: 1ms.. execfn ...

Ways to handle deprecation alerts issued by npm

Whenever I use npm to install a package, it seems like I always receive a warning similar to this: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="214c484f484c4055424961100f110f11">[email protected]& ...

What is the most effective way to organize an API structure in ExpressJs for a system with numerous chapters containing various topics, each of which has its own

How should I design the API structure for a system with multiple chapters, each containing multiple topics and one PDF for each topic? I am working with Express. In my database, I have two tables - one for chapters and another for topics and their associa ...

Can you explain the contrast between "npm update -g", "npm upgrade -g", "npm install -g npm", and "n stable"?

It appears that my npm is outdated and there are multiple ways to update it: sudo npm update -g # => npm 3.8.6 sudo npm upgrade -g # => npm 3.8.7 sudo npm install -g npm sudo npm cache clean -f && sudo npm install -g n && sudo n ...

Transfer the user object to a designated route in Express

Is there a way to pass the user object to a specific route before redirecting to that route? I have attempted using the solution mentioned here, but unfortunately, it is returning undefined. The scenario involves redirecting the user from the signup route ...

Error: The property 'image' is trying to be accessed from an undefined object and cannot be read

I am having trouble with my source code and can't seem to identify the issue - seeking assistance. I tried implementing some solutions that I came across but they didn't yield any positive results. var express = require('express'); var ...

The Power of ExpressJS Redirect

When using the res.redirect( url ) method, will it also pass along any previous parameters to the destination URL? For example, if I send a POST request with JSON parameters and then redirect that request to another server, will the redirected server rece ...

How can I redirect a remote image URL to a local folder during development?

Currently, I am pulling image URLs from a database that was dumped from the production server. An example of one of these URLs is https://example.com/imageStorage/photo.jpg. These URLs are then used to display images in HTML templates using the following f ...

Encountering numerous issues while trying to install npm on a Linux system

I've been scouring forums for a solution to my problem, but haven't found anything that works. Can anyone help? I recently installed Ubuntu and added Vim, Git, and Node.js. Now I'm trying to install npm, but running into multiple errors: k ...

Ways to verify the presence of an item in a MonoDB array

My MongoDB model looks like this: const userSchema = new Schema = ({ name: { type: String }, company: [ companyId: { type: String, }, movies: [ { genre: { type: String, enum: [ ...

What is the best way to display all mysql rows in Node.js using handlebars templating?

Here is the code snippet I used to share only the first row (jack) from MySQL: node: const express = require("express"); const app = express(); app.set("view engine","hbs") const mysql = require("mysql") const db = m ...

An issue arose while installing a node.js package called Hummusjs

I'm encountering an issue while attempting to install the 'hummus' package using the command: npm install -g hummus The error message from the logs reads as follows: 1926 verbose stack Error: <a href="/cdn-cgi/l/email-protection" class ...

Issues arise when attempting to delete messages that have already been retrieved

Having trouble removing messages from a specific user without any success: bot.js client.on("message", (message) => { if (message.content === '$deleteuser') { message.channel.fetchMessages({limit: 10}).then(collec ...

Encountering an EACCES error when running Node (Express) on a Linux operating system

I am currently developing a Node.js application using Expressjs, and I am facing an issue when trying to run the app on a new Ubuntu installation (I have just installed git and Node v0.10.19). Unfortunately, I encounter the following error message when at ...

Guide to delivering static files from a different directory using express

I'm facing an issue with displaying the public folder from index.js using express. Initially, I tried using app.use(express.static('public')) and it worked on my local machine. However, when I deployed it, the functionality stopped working. ...