HapiJS - placing controllers in routes - javascript

Hapi is something new for me and actually I'm trying to create a good structure for my project.
I've this file: routes/catalogs.js
"use strict";
const Boom = require('boom');
const uuid = require('node-uuid');
const Joi = require('joi');
exports.register = function(server, options, next) {
server.route({
method: 'GET',
path: '/catalogs',
handler: function(request, reply) {
var catalogs = server.app.mongodb.collection('catalogs');
catalogs.find({}).toArray(function(err, docs) {
reply(docs);
});
}
});
return next();
};
exports.register.attributes = {
name: 'routes-notifications'
}
But instead left all the code on the same file for routing ,I'd like to place the code that's do all the database task in a controller, something similar to this: https://github.com/agendor/sample-hapi-rest-api/blob/master/src/controllers/task.js
but I really can't understand how to do it maybe because on the example, the libs for database is very different and it's mess me. can someone help me to convert my controle to be used with config : {handler: ?
ty !

If you look at this file it shows how you can break mongodb handlers which are added to hapi routes here. The aim of this module was to generate data models and methods from json schemas.

Related

How can I use filtering by using Node.js and Mysql

I'm new at Node.js and trying to solve a routing problem. I need to paginate, search and filter some group of data from my database. Pagination part is done, filtering is done but routing part of it became a problem for me. I did not understand the logic of routing in Node.js. Here is my codes:
my controller :
exports.projects_filter = async(req,res)=>{
try {
let sql = "select * from proje_detaylari where proje_kategorisi='Üretim'";
const allDB = await projeler_db.query(sql) ;
const kategori_üretim = allDB[0] ;
res.render('proje_kütüphanesi',{
kategoriler: kategori_üretim
})
} catch (error) {
}
}
my routing :
router.get("/proje_kutuphanesi", projectController.project_paginator, function (req, res) {
//all projects are displayed and paginated in the front-end
});
router.get("/proje_kutuphanesi", projectController.projects_filter, function (req, res) {
//i want filtering in here
});
My question is how can I implement filter routing something like
/proje_kutuphanesi/?category=something
I mostly understand the logic but routing at the above (pagination routing) is the one which prevents it.

node.js express and regular expressions

Hi friends I am working with node.js and express. I have some endpoints and inside there are dynamic files every file have a name of an IP for example services/192.168.0.1.html, service/192.168.0.11.html, service/192.168.0.15 etc. So I want to make a dynamic route like this code:
app.get('/endpointej/**REGEXP**forIP.html', (req, res) => {
var ruta = {
root: path.join(__dirname + 'endpoint/)
}
res.sendFile("IPfiledinamic.html",ruta)
});
Can some one help me out please ?
Regards
You can use something like
// route is for GET /test/1.1.1.1.html, but not for GET /test/1.2.3.html
app.get(/test\/([0-9]{1,3}\.){3}[0-9]{1,3}\.html/, (req, res) => {
const ipRegex = /^\/test\/((?:[0-9]{1,3}\.){3}[0-9]{1,3})\.html$/
// do more here...
res.status(200).send(`matches, ${req.url.match(ipRegex)}`)
})

How to import object to another file?

I'm using Node.js to build a web application.
I have two files. Server.js - where I call the server to go online etc. And the other one is a file which includes a big object with data. I imported the file with data into server.js, I get the object in postman when I set the website to be live. But I can't dive inside the object to get the data inside the object. The error I'm getting says that the variable where my data is stored is not defined.
I think the fix is to import albumsData variable into server.js, but im completely stuck and can't find how to do it. If anyone has any idea, please share.
albumsData.js
const express = require('express');
const router = express.Router();
let albumsData = {
filled with data
}
router.get('/albumData', (req, res) => {
res.send(albumsData);
});
module.exports = router;
Server.js
app.use(require('./api/albumData/unikkatilData'))
app.use((req, res) => {
res.status(404)
.send(albumsData)
});
app.listen(4000, () => {
console.log('hello worldd')
})
If you want the albumsData object then you can do it like this:
In you albumsData.js file:
const albumsData = {
// Bunch of data
}
module.exports = albumsData
Then in your server.js file:
const albumData = require('./api/albumsData') // Make sure this path points directly to the albumsData.js file
move enter code here to new file (ex utils.js)
and export it exports.albumsData = albumsData; then you can call it
with const utils = require('./utils') ; utils.albumsData

Get middleware mount point from request in Express

I have an Express application with a router, here is the example of the router:
const router = require('express-promise-router')();
const users = require('./users');
const validate = require('./validate');
router.get('/users', users.list);
router.get('/users/:id', users.get);
// other routes here
module.exports = router;
Now I want to add a middleware that validates each query, like that (this is not the working example, it's just to show the idea of what I want to accomplish):
const schemas = {
'/users': 'some validation schema',
'/users/:id': 'another validation'
}
module.exports = (req, res, next) => {
const url = req.originalUrl; // This is where I'm stuck.
if (!schemas[url]) {
// throw new error that validation failed
}
// validating somehow
if (!req.validate(schemas[url])) {
// throw new error that validation failed
}
return next();
}
And for this, I need to get the middlelware mount folder (like '/users/:id' for '/users/557'). I've tried to use req.originalUrl, but it returns the full URL path instead of the mount folder.
How can I achieve this? And if there's no way, how can I write my validation middleware another way to make it work?
Inside req.route you will get the path of API.
Check this screenshot

Koa pass data from server to client

I want to pass through some environment variables from a Koa server to the client. In express I could do something like res.render('index', { data: 'someData' }); and then I could access data. In Koa I can't see how to do this. It mentions using context.state but I can't find any example of how to retrieve this in the client.
You can do something similar in Koa, you just need to use the right middleware. Try out koa-views if you're using one of the supported engines.
Here is a full example (this example assumes you're using Koa v1 and EJS as your templating engine):
app.js
const Koa = require('koa')
const views = require('koa-views')
const router = require('./routes')
const app = new Koa()
app.use(views(__dirname + '/views', { extension: 'ejs' }))
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)
routes.js
const router = require('koa-router')()
router.get('/', function * () {
yield this.render('index', { title: 'Home' })
})
router.get('/about', function * () {
yield this.render('about', { title: 'About' })
})
module.exports = router
Just change the extension argument you pass to the middleware based on which templating engine you are using.

Categories