How do I add parameters to long-form return requests in module.exports routes? - node.js

I'm coding for an API connection area, that's predominately graphql but needs to have some REST connections for certain things, and have equivalent to the following code:
foo.js
module.exports = {
routes: () => {
return [
{
method: 'GET',
path: '/existing_endpoint',
handler: module.exports.existing_endpoint
},
{
method: 'POST',
path: '/new_endpoint',
handler: module.exports.new_endpoint // <--- this not passing variables
}
]
},
existing_endpoint: async () => {
/* endpoint that isn't the concern of this */
},
new_endpoint: async (req, res) => {
console.log({req, res})
return 1
}
}
The existing GET endpoint works fine, but my POST endpoint always errors out with the console of {} where {req, res} should have been passed in by the router, I suspect because the POST isn't receiving. I've tried changing the POST declaration in the routes to module.exports.new_endpoint(req, res), but it tells me the variables aren't found, and the lead-in server.js does have the file (it looks more like this...), and doing similar with the server.js, also getting similar results, implying that's probably wrong too. Also, we have a really strict eslint setup, so I can't really change the format of the call.
Every example I've seen online using these libraries is some short form, or includes the function in the routes call, and isn't some long form like this. How do I do a POST in this format?
/* hapi, environment variables, apollog server, log engine, etc. */
/* preceeding library inclusions */
const foo = require('./routes/foo')
const other_route = require('./routes/other_route')
const startServer = async () => {
const server = Hapi.server({port, host})
server.route(other_route.routes())
server.route(foo.routes())
}

This is a bug with Hapi in node v16. I just opened an issue.
Your current solutions are either:
Upgrade to Hapi v20
Use n or another method to downgrade to node v14.16 for this project. I can confirm that POST requests do not hang in this version.

Related

How to process JS file returned from Express response.sendFile()

I have an API which uses Node.js + Express on the backend.
For one of the API endpoints, I'd like to use the Express response object method of "sendFile", documented here:
https://expressjs.com/en/api.html#res.sendFile
The API should return a Javascript file through the sendFile method.
What I can't figure out is how to read in the .js file on the front end so that I can use the JavaScript functions defined in the file. The sendFile portion appears to be working -- it's just the use of the file which I can't figure out.
Here's what I'm doing on the backend:
app.get("/api/member", async (req, res) => {
options = {
root: path.join(__dirname, '/static'),
dotfiles: 'deny'
}
res.sendFile("member.js", options, (err) => {
if (err) {
console.log(err)
next(err)
} else {
console.log('Sent file')
}
})
});
This seems to be working fine, as I can navigate to the endpoint on my localhost and it loads the JS file. The file member.js simply contains some javascript function definitions.
But, I can't figure out how to consume/use the file once it arrives to the front end.
Here's what I have currently on the frontend:
async function refreshJS() {
const url = `${baseUrl}/member`;
const response = await fetch(url, { credentials: "include" });
const script = document.createElement("script")
script.type = "text/javascript"
script.src = response.body
document.head.appendChild(script)
eval(script)
}
I've spent a lot of time looking through the console/debugger to find the text associated with the JS functions -- but they're nowhere to be found.
I've tested this general framework by loading JS files locally through the console and it worked, so I think it's wrapped up in a misunderstanding of where the JS functions live in the API response. For example, if I replace the command above of:
script.src = response.body
with
script.src = "member.js"
then everything works fine provided I have the file locally.
The examples that I've reviewed seem to deal exclusively with sending an HTML file which is loaded on the frontend. But, I can't find supporting documentation from the fetch API to understand how to use the JS file contents.

Is it possible to create two identical routes with a different param name using Fastify?

In my application, I would like to have two routes that match the following paths
fastify.get('/thing/:id', async () => {})
fastify.get('/thing/:name', async () => {})
I tried giving the ':id' path a regex, but Fastify still recognized them as duplicate routes. Is it possible to accomplish this aside from running a regex in the handler to determine if it is an id or a name?
EDIT: I failed to mention that I am familiar with the Fastify documentation. I was hoping to discover something that is not currently documented.
A nice alternative would be if it were possible to declare alternate params at the same path level and to have the schema determine which param applies. For example:
'/thing/:id|:name' and then have the params schema or be the determining factor, or separate regexs in the route like, '/thing/:id()|:name()'.
Anyway, would be cool.
That is not possible. Each has to be different from other somehow. But what you can do is Route Prefixing.
Like this
// server.js
const fastify = require('fastify')()
fastify.register(require('./routes/v1/things'), { prefix: '/v1' })
fastify.register(require('./routes/v2/things'), { prefix: '/v2' })
fastify.listen({ port: 3000 })
// routes/v1/things.js
module.exports = function (fastify, opts, done) {
fastify.get('/thing/:id', handler_v1)
done()
}
// routes/v2/things.js
module.exports = function (fastify, opts, done) {
fastify.get('/thing/:name', handler_v2)
done()
}
Fastify will not complain because you are using the same name for two different routes, because at compilation time it will handle the prefix automatically (this also means that the performance will not be affected at all!).
Now your clients will have access to the following routes:
/v1/thing/:id
/v2/thing/:name
You can do this as many times as you want, it also works for nested register, and route parameters are supported as well.
You can read more about fastify routes here.

How to remove authentication for introspection query in Graphql

so may be this is very basic question so please bear with me. Let me explain what I am doing and what I really need.
EXPLANATION
I have created a graphql server by using ApolloGraphql (apollo-server-express npm module).
Here is the code snippet to give you an idea.
api.js
import express from 'express'
import rootSchema from './root-schema'
.... // some extra code
app = express.router()
app.use(jwtaAuthenticator) // --> this code authenticates Authorization header
.... // some more middleware's added
const graphQLServer = new ApolloServer({
schema: rootSchema, // --> this is root schema object
context: context => context,
introspection: true,
})
graphQLServer.applyMiddleware({ app, path: '/graphql' })
server.js
import http from 'http'
import express from 'express'
import apiRouter from './api' // --> the above file
const app = express()
app.use([some middlewares])
app.use('/', apiRouter)
....
....
export async function init () {
try {
const httpServer = http.createServer(app)
httpServer
.listen(PORT)
.on('error', (err) => { setTimeout(() => process.exit(1), 5000) })
} catch (err) {
setTimeout(() => process.exit(1), 5000)
}
console.log('Server started --- ', PORT)
}
export default app
index.js
require('babel-core')
require('babel-polyfill')
require = require('esm')(module/* , options */)
const server = require('./server.js') // --> the above file
server.init()
PROBLEM STATEMENT
I am using node index.js to start the app. So, the app is expecting Authorization header (JWT token) to be present all the times, even for the introspection query. But this is not what I want, I want that introspection query will be resolvable even without the token. So that anyone can see the documentation.
Please shed some light and please guide what is the best approach to do so. Happy coding :)
.startsWith('query Introspection') is insecure because any query can be named Introspection.
The better approach is to check the whole query.
First import graphql and prepare introspection query string:
const { parse, print, getIntrospectionQuery } = require('graphql');
// format introspection query same way as apollo tooling do
const introspectionQuery = print(parse(getIntrospectionQuery()));
Then in Apollo Server configuration check query:
context: ({ req }) => {
// allow introspection query
if (req.body.query === introspectionQuery) {
return {};
}
// continue
}
There's a ton of different ways to handle authorization in GraphQL, as illustrated in the docs:
Adding middleware for express (or some other framework like hapi or koa)
Checking for authorization inside individual resolvers
Checking for authorization inside your data models
Utilizing custom directives
Adding express middleware is great for preventing unauthorized access to your entire schema. If you want to allow unauthenticated access to some fields but not others, it's generally recommended you move your authorization logic from the framework layer to the GraphQL or data model layer using one of the methods above.
So finally I found the solution and here is what I did.
Let me first tell you that there were 2 middle-wares added on base path. Like this:
app //--> this is express.Router()
.use(jwtMw) // ---> these are middlewares
.use(otherMw)
The jwtMw is the one that checks the authentication of the user, and since even introspection query comes under this MW, it used to authenticate that as well. So, after some research I found this solution:
jwtMw.js
function addJWTMeta (req, res, next) {
// we can check for null OR undefined and all, then check for query Introspection, with better condition like with ignore case
if (req.body.query.trim().startsWith('query Introspection')) {
req.isIntrospection = true
return next()
}
...
...
// ---> extra code to do authentication of the USER based on the Authorization header
}
export default addJWTMeta
otherMw.js
function otherMw (req, res, next) {
if (req.isIntrospection) return next()
...
...
// ---> extra code to do some other context creation
}
export default otherMw
So here in jwtMw.js we are checking that if the query is Introspection just add a variable in req object and move forward, and in next middleware after the jwtMw.js whosoever wants to check for introspection query just check for that variable (isIntrospection, in this case) and if it is present and is true, please move on. We can add this code and scale to every middleware that if req.isIntrospection is there just carry on or do the actual processing otherwise.
Happy coding :)

How to call Hapi plugin function from another

In Hapi (v17 if it makes any difference), what is the correct way to call a function in a plugin from another ?
Let's say I've started writing a wrapper plugin around Nodemailer :
'use strict';
const Nodemailer = require('nodemailer');
exports.plugin = {
name: 'mailerWrapperPlugin',
version: '0.0.1',
register: async function (server, options) {
}
};
What would be the correct way to expose plugin functions elsewhere in Hapi (i.e to the Hapi instance itself, but perhaps more importantly, to other plugins loaded by Hapi).
I'm finding the Hapi documentation a bit sparse, especially in relation to plugins.
So, for example, if my Nodemailer wrapper had a sendMail() function, how would I make that available in another plugin I've written ?
P.S. I'm a bit of a Node.JS/Hapi newbie, so treat me gently ! I'm testing this out because I'm thinking of migrating from PHP to Hapi for future backend applications.
You can use server.methods object. The doc says:
Server methods are functions registered with the server and used
throughout the application as a common utility. Their advantage is in
the ability to configure them to use the built-in cache and share
across multiple request handlers without having to create a common
module.
Now this is your first plugin:
const Nodemailer = require('nodemailer');
exports.plugin = {
name: 'mailerWrapperPlugin',
version: '0.0.1',
register: async function (server, options) {
server.method('sendMail', (subject, to, body) => {
// compose and send mail here
});
}
};
and this is your second, and make sure this is loaded after the first one.
exports.plugin = {
name: 'anotherPlugin',
version: '0.0.1',
register: async function (server, options) {
server.methods.sendMail("Hello", "test#test.com", "Sup?");
}
};
That's it.
Also you can use server.decorate object as well. Its doc says:
Extends various framework interfaces with custom methods where:
server.decorate may add methods to several other objects like routes, request, server and response object.
If we go back to your plugin:
exports.plugin = {
name: 'mailerWrapperPlugin',
version: '0.0.1',
register: async function (server, options) {
server.decorate('server', 'sendMail', (subject, to, body) => {
});
}
};
and your second plugin which was loaded after the first one!
exports.plugin = {
name: 'anotherPlugin',
version: '0.0.1',
register: async function (server, options) {
server.sendMail("Hello", "test#test.com", "Sup?");
}
};
The difference between them, the server.methods object add custom fields to server.methods object but with the server.decorate you can directly extend your server or request objects. Use which one is more clear to you, I prefer server.decorate generally.

NodeJS/Express API versioning

I'd like to set up an API versioning, similar to how Stripe does it but I'm not quite sure how to make express do what I need. https://stripe.com/docs/api#versioning
What I'm looking for is, the proper route would be something like:
/api/v1/call
The kicker is, I'd like them to pass in a version revision like stripe allows, so if they sent a header like "API-Version: 2015-08-15", it would map to that specific version of the major version. So, v1 but the version updated on 2015-08-15.
Essentially, if there is an update to the API call that is not backwards compatible, I'd roll a new version for that particular call. Express would be smart enough to know that if a version isn't passed, use the latest. If a version is passed, use the latest version for each call up until the version date.
I'd assume the directory structure would be something like:
/router/
/router/v1
/router/v1/call
/router/v1/anotherCall
And maybe in the call directories, there is a index that checks for the header version and uses the proper file.
So maybe for instance
/router/v1/call/index.js
/router/v1/call/20150810.js -- First version
/router/v1/call/20150815.js -- Updated version that isn't backwards compat.
Thoughts? Ideas?
If you are managing version in routes(url) and client sends version in headers then express doesn't provide any elegant way to handle versioning. Also, doing versioning in routes is not restful.
I wrote an simple npm module to solve this problem. https://www.npmjs.com/package/express-routes-versioning
Express routes versioning
Module allows individual routes to be versioned separately. It is agnostic about specific versioning strategies and allows the application to set the version, so you should be able to parse version from headers and set it to req.version in a middleware. It supports semver versioning format and symbols to map multiple versions to single function.
Sample code on how it works.
var app = require('express')();
var versionRoutes = require('express-routes-versioning')();
app.listen(3000);
app.use(function(req, res, next) {
//req.version is used to determine the version
req.version = req.headers['accept-version'];
next();
});
app.get('/users', versionRoutes({
"1.0.0": respondV1,
"~2.2.1": respondV2
}));
// curl -s -H 'accept-version: 1.0.0' localhost:3000/users
// version 1.0.0 or 1.0 or 1 !
function respondV1(req, res, next) {
res.status(200).send('ok v1');
}
//curl -s -H 'accept-version: 2.2.0' localhost:3000/users
//Anything from 2.2.0 to 2.2.9
function respondV2(req, res, next) {
res.status(200).send('ok v2');
}
By default, if the client version doesn't match the version provided in the server, module servers the latest version callback available in that route. This behavior can be overridden by providing an additional callback. More info and source code available at https://github.com/Prasanna-sr/express-routes-versioning
This how I'm handling versioning. Basically you create a new router object and use app.use so that only /api/v1 routes are sent to it. I then use a "fall through" route which catches anything which didn't match and returns a unknown command message. I also renamed the res.json function so that I can add APIversion = 1 to each object that went out (That's in the router.use function call).
Whenever I have a v2 api I'll do this exact same thing but create a new file and use a different app.use path. See below:
app.js
....
app.use('/api/v1', require('./api1.js'));
....
api1.js
var express = require('express');
var router = express.Router();
router.use(function (req, res, next) {
res._json = res.json;
res.json = function json(obj) {
obj.APIversion = 1;
res._json(obj);
};
next();
});
/* ADD ALL YOUR ROUTES HERE */
//Done - catch all - return command failed
router.get('*', function (req, res) {
res.status = 404;
res.json({
success: false,
message: 'Unknown command'
});
});
module.exports = router;
https://medium.com/#vgjohn/node-js-api-versioning-with-totoro-node-c2ea1ef3dfba
There's a small package called totoro-node that helps deal with route management for api versioning. It might help to solve some of the problems you're facing. You just write a simple api definition like this and you can control which endpoints or api versions to deprecate or inherit into subsequent api versions. https://www.npmjs.com/package/totoro-node
var app = express()
app.use('/api', totoro.rain({
v1: {
"/oAuth": {
method: "GET",
deprecated: true,
endpointImplementation: routes.authRoutes.oAuth
},
"/ssoToken": {
method: "GET",
endpointImplementation: routes.authRoutes.sso
}
},
v2: {
"/ssoToken": {
method: "GET",
endpointImplementation: routes.authRoutes.sso
}
}
}))
I think you could set a middleware before all your routes to check headers.
app.use("*",function (req,res,next) {
var headers = req.headers
//Process
req.apiVersion = "version"
next()
}
//all your routes
this is a example , but you could manipulate headers in your router instance and then pass req to other route
//v1/call/index.js
//all your routes
app.use("/v1/call",function (req,res){
var version = req.apiVersion;
//execute something depending on version
})

Resources