Steps to invoke another service (function) prior to calling the res.view() function in sails JS:

I am looking to execute a separate function, like a Service function, before Sails renders the page into HTML. Please refer to the controller code below...

var MYController = {
   index: function(req, res, next) {

      req.flash("error", "Testing hello world"); 
      MyCustomServices.myFunction( req, res );
      res.view();
   }
}

To include my service function, check api/services/MyCustomServices.js

exports.myFunction = function( req, res ){
   Test.findOne({ code : "CODE" }, function(err, resp) {
        if ( resp ) {
            res.locals.TEST = resp;
        }
   });

   var msg = req.flash('error');
   res.locals.ERROR = msg.length>0 ? msg : "" ;

};

In this case, there is an additional process that needs to run before res.view() when calling MyCustomServices.myFunction( req, res );

The issue is that every time I call the res.view() function, I have to add this line in all my controller actions.

I attempted to add MyCustomServices.myFunction( req, res ); in express.js, but it didn't work as expected. It seems like it should be in express, but I'm not sure what codes are needed to be added.

The tasks performed by MyCustomServices.myFunction( req, res ) include:

  1. Fetching data from MongoDB using a query to Sails.
  2. Parsing req.flash messages to pass them to views for display.

Does anyone have ideas on how to resolve this?

Answer №1

If your Service completion triggers the need to use res.view, one possible solution is to eliminate res.view from the controller and integrate it directly into the service:

var MYController = {
  index: function(req, res, next) {
    req.flash("error", "Testing hello world"); 
    MyCustomServices.myFunction( req, res );
    //res.view();
  }
}

exports.myFunction = function( req, res ){
   Test.findOne({ code : "CODE" }, function(err, resp) {
        if ( resp ) {
            res.locals.TEST = resp;
            res.view(); //TADA
        }else {
            /* Handle Error */
        }
   });

   var msg = req.flash('error');
   res.locals.ERROR = msg.length>0 ? msg : "" ;

};

Answer №2

Two Possible Choices

Incorporate a callback into your service for added functionality

var NewController = {
   display: function(request, response, next) {

      request.flash("error", "Testing hello world"); 
      MyCustomServices.myFunction( request, response, function(){
          return  response.view();
      } );

   }
}

exports.myFunction = function( request, response, callback ){
   Test.findOne({ identifier : "IDENTIFIER" }, function(error, result) {
        if ( result ) {
            response.locals.DATA = result;
            return callback()
        }
   });

};

-- or (as suggested in your feedback) --

You have the option to implement a custom response handler in your application. Visit for more information.

You may substitute res.view() with res.ok() and adjust api/responses/ok.js according to your requirements.

If you prefer not to modify ok.js, you can create your own customized response instead.

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

Node.js server becomes unresponsive when attempting to upload files with FineUploader

After spending more than two weeks troubleshooting a persistent bug, I'm still unable to identify the root cause. The issue revolves around a page utilizing FineUploader for uploading multiple files. Each item in a collection requires its own set of i ...

The electron program is unable to locate the package.json module

I am new to electron and attempting to run an express app for the first time. However, I encountered this error: Need assistance updating code Error: Cannot find module 'C:\package.json' at Module._resolveFilename (module.js:440:15) ...

Accessing specific documents in Firebase cloud functions using a wildcard notation

Currently, I am working on implementing Firebase cloud functions and here are the tasks I need to achieve: Monitoring changes in documents within the 'public_posts' collection. Determining if a change involves switching the value of the &ap ...

Looking to import a 3D gltf model using the input tag in an HTML file for use in three.js (JavaScript), but encountering an issue with the process

I am trying to upload my 3D model from an HTML input tag, but I keep encountering this error message: t.lastIndexOf is not a function Here's the HTML code I am using: <input type="file" id="MODEL" /> <button onclick=&qu ...

"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue: The module has no default export I tried importing using curly braces and exporting with module.exports, but neither solution worked. contactController.ts const contacts: String[ ...

Looping through alert items

Below is the code snippet I am working with: <tr ng-repeat="sce in users"> <td> <a href="/test/delete?id={{sce.id}}" onclick="return confirm('You really want to delete'+ {{sce.name}} + 'from list');" > ...

What steps can I take to resolve my password validation rule when confirming during sign-up?

Utilizing react-hook-form in combination with Material-UI for my sign-up form has been a challenge. I am currently working on implementing a second password field to confirm and validate that the user accurately entered their password in the initial field, ...

Utilizing jQuery to iterate over dynamically generated elements sharing a common class

Whenever I click a button, numerous div elements are dynamically created. <table> <tbody id="ProductDetail"></tbody> </table> These dynamically created divs have an associated Amount value that is added upon creation. funtion ...

Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results. Initially, the following approach worked well: const value = 'TTest90()'; const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2 ...

What is the goal of JSON.parse(JSON.stringify(x))?

During my recent project work, I stumbled upon the following code snippet: let newParams = JSON.parse(JSON.stringify(initialParams)); I'm curious - what exactly does this code achieve? ...

Error: The Express.io library could not detect the socket.io.js file

Encountering an issue with Express.io while trying to create a simple chat application. Struggling to include socket.io.js, resulting in an error... Recently added Express.io to a new Express project. The errors I am facing are as follows: GET http://* ...

Is it possible to share the passport.js session from one server to access multiple others?

I am currently utilizing passport.js in conjunction with an express server. The example repository is running on port 3000. My goal is to enable the usage of port 3000 for passport login, similar to the example, while establishing a session that can work ...

Obtaining data objects with Angular 2 from JSON

Recently, I received a URL that includes data arrays in JSON format. My goal is to retrieve and utilize all elements within it: However, when attempting this, I end up with everything but nothing specific. For instance: How can I access data.name or data. ...

Ensuring session data is updated when saving a mongoose model

I am facing a challenge with updating express session data in the mongoose save callback. Is there a way to access and modify the session data from within line 4 of the code? app.get('/', function(req, res){ var newModel = new Model(somedata); ...

Speedy start-up with callback for asynchronous initialization

Currently, I am utilizing express to dynamically add routes based on data stored in a MongoDB configuration. const app = require('express')(); const mongoose = require('mongoose'); var proxyHandler = { paths: [ '/demoservic ...

ImageMapster for perfect alignment

I'm struggling with centering a div that contains an image using imagemapster. When I remove the JS code, the div centers perfectly fine, indicating that the issue lies with the image mapster implementation. It's a simple setup: <div class=" ...

Tips on customizing the appearance of mat-card-title within a mat-card

Is there a way to truncate the title of a mat card when it overflows? I tried using the following CSS: overflow:hidden text-overflow:ellipsis white-space: nowrap However, the style is being overridden by the default mat-card style. I attempted to use mat ...

Steps for deploying a Next.js frontend and a separate Express backend:1. First,

I am in the process of developing an application that utilizes next.js for the frontend and a standalone backend server built on express. As I plan for production deployment, I am concerned about costs and the most efficient approach to take. Although I ha ...

Enhancing jQuery Functionality with Parameter Overrides

While it may seem like a simple question, I am new to writing jQuery plugins and could use some clarity on scope rules in JavaScript. My goal is to create a jQuery plugin that interacts with the Stack Overflow API. I have started exploring the Flair API f ...

Issue with updating bound property correctly when dynamically generating components using v-for in Vue.js

Encountered a challenge with vue.js and seeking guidance on the best approach to address it. Here's a concise summary of the issue: Situation Data is fetched from a rest API, handled by a class called DataLoader using javascript prototype syntax. Th ...