Saturday, 9 May 2020

First node express project. Wanting to put functions (not routes) into separate files (what to export?)

I'm really enjoying using Node with express for a new project, but its often I get really confused about some concepts.Project is simple: user fills out form, it gets submitted and inserted into sql database. I actually have this part working, but the logic to get data from and insert into the database is in my routes/index.js file. For example when the index route is called (router.get('/')) I'm reaching out to a database table to grab some values to fill a dropdown with before rendering the page (this works beautifully). This code is in my main routes page and I'd like to separate the logic (and so I can reuse it). Here's that route:// ./routes/index.js const express = require('express'); const router = express.Router(); const sql = require('../db'); router.get('/', (request, response, next) => { sql.query('SELECT values FROM table where value = ?', [x], (err, rows, fields) => { if (err) throw new Error(err); response.render('home', {layout: 'base', template: 'home-template', dropdownList: rows}); }); }); I'd like to take the sql.query and add it to a middleware in a separate file (in my middleware folder) and return the results as an object to use in the response.render.Here's what I've tried without luck: I moved that query to a new file in my middleware folder. It looks like this:./middleware/dropdowns.jsconst express = require('express'); const sql = require('../db'); const dropdownValues = (function getDropdownValues(x) { sql.query('SELECT values FROM table where x = ?', [x], (err, rows, fields) => { if (err) throw new Error(err); return rows; }); }); modules.exports = dropdownValues; Then I required this into my main app.js and tried to just console.log the values but I get the error 'getDropdownValues is not a function'.app.js const express = require('express'); const app = express(); //init express const routes = require('./routes'); const dropdownValues= require('./middleware/dropdowns');app.use(dropdownValues, (req, res, next) => { console.log(dropdownValues.getDropdownValues('x')); next(); }); I am completely aware that this is due to the poverty of my knowledge of node and express at the moment, but I'm hoping to get past these hurdles with practice. I've read a lot of tutorials and articles on how to achieve this, but it seems everyone has a different method, and when I try to use any one it clashes with some other way I've configured something else.In short, I'm trying to separate my middleware in files with functions in order to reuse in my project. Specifically functions that will accept parameters from things like the request and return data.Many thanks!

Submitted May 09, 2020 at 04:11PM by MotorBoats

No comments:

Post a Comment