How to move an #hapi plugin out to its own separate file - node.js

I am upgrading the Node version of my system and have got to the point of updating hapi to #hapi/hapi. I am using Node version 14.0.0 and #hapi/hapi version 20.2.2
I've written a simple server with just one route, which works perfectly:
'use strict';
const Hapi = require('#hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
// await server.register(require('./plugins'))
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
});
await server.start();
console.log(`'Test' server running on Node ${process.version} at:`, server.info.uri);
};
init();
However, if I uncomment the server.register call and comment out the server.route code I get an error. The file ./plugins/index.js looks like this:
'use strict';
const report = {
name: 'report',
version: '1.0.0',
register: async function (server, options) {
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
});
}
}
The error I am getting from the #hapi server is this:
(node:4793) UnhandledPromiseRejectionWarning: Error: Invalid plugin options {
"plugin": {
"register" [1]: -- missing --
}
}
[1] "plugin.register" is required
It looks like a very simple issue, but I cannot find anything relatively modern on the Internet to help me out. Please can someone just point me in the right direction? - thank you.
EDITED: I have moved #hapi/hapi up to the latest version, 21.1.0, and Node up to 18.12.1 but still get the same message.

Related

Jest+NextJs: You should only use "next/router" on the client side of your app

I'm mocking the next/router dependency in my Jest+React-testing-libray tests as I always have:
import * as nextRouter from 'next/router';
export const routerData = {
pathname: '/users/create',
route: '/users/create',
query: { },
asPath: '/users/create',
isFallback: false,
basePath: '',
isReady: true,
isPreview: false,
isLocaleDomain: false,
events: {},
};
// mock router
jest.mock('next/router');
nextRouter.useRouter.mockImplementation(() => (routerData));
describe('a component that requires next/router, () => ... );
This had been working correctly but after updating to NextJs 12.2.0 I get this warning:
No router instance found.
You should only use "next/router" on the client side of your app.
This warning makes all my tests with the mocked router to fail.
Ideas to fix this?
Well, it appears that this is not related to 12.2.0. Somehow my last version of Next - 12.0.0 - wasn't thrownig this error but other older versions did.
Thanks to bistacos for the response here.
const useRouter = jest.spyOn(require('next/router'), 'useRouter');
useRouter.mockImplementation(() => ({
pathname: '/',
...moreRouterData
}));

Hapi.js Cannot read property 'statusCode' of null

I'm creating a node.js api server using hapi.js and mongodb and I'm having some trouble to get it working on Amazon EC2.
Running it locally works, but if I run it on an EC2 instance I'm getting the error TypeError: Cannot read property 'statusCode' of null
The complete stacktrace is the following:
TypeError: Cannot read property 'statusCode' of null
at Request._finalize (/home/ec2-user/backend/node_modules/#hapi/hapi/lib/request.js:497:31)
at Request._reply (/home/ec2-user/backend/node_modules/#hapi/hapi/lib/request.js:434:18)
at Request._execute (/home/ec2-user/backend/node_modules/#hapi/hapi/lib/request.js:280:14)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
The strange part is that GET requests are working while PUT, POST and DELETE are throwing the above error.
I've setup the server.js as follow:
...
const init = async () => {
const server = Hapi.server({
port: 3000,
});
//server.route(routes);
server.route([
{
method: "GET",
path: "/test",
handler: async (request, h) => {
return "workin GET";
},
},
{
method: "PUT",
path: "/test",
handler: async (request, h) => {
return "workin PUT";
},
},
{
method: "POST",
path: "/test",
handler: async (request, h) => {
return "workin POST";
},
},
{
method: "DELETE",
path: "/test",
handler: async (request, h) => {
return "workin DELETE";
},
},
]);
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Any solution?
I've found out that on the EC2 instance I had installed node version 15.5.0 which apparently is not compatible with the latest version of hapi.js (20.0.2).
To fix the issue just install node version 14.15.3.
This is fixed in #hapi/hapi v20.2.1: https://github.com/hapijs/hapi/issues/4319.
Just remove #hapi/hapi and re-install it

Cannot set uncompiled validation rules without configuring a validator

I have downloaded a learning project so it is not my code, but when I want to start it getting this error. I tried to debug a little bit by myself but as I'm new to Nodejs so having a problem here...
Error: Cannot set uncompiled validation rules without configuring a validator
at Object.module.exports.register (/home/antonp/Desktop/pizza-luvrs/routes/index.js:25:10)
at startServer (/home/antonp/Desktop/pizza-luvrs/index.js:12:10)
here is the link for the full project. Github repo
index.js
const Hapi = require('#hapi/hapi')
const plugins = require('./plugins')
const routes = require('./routes')
async function startServer () {
const server = Hapi.Server({
port: process.env.PORT || 3000
})
await plugins.register(server)
routes.register(server)
try {
await server.start()
console.log(`Server running at: ${server.info.uri}`)
} catch (err) {
console.error(`Server could not start. Error: ${err}`)
}
}
process.on('unhandledRejection', err => {
console.log(err)
process.exit()
})
startServer()
Your issue is due to a change in hapi. Try changing the following code in pizza-luvrs-master/routes/login.post.js
validate: {
payload: {
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().min(3).max(30).required()
}
}
to
validate: {
query:Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().min(3).max(30).required()
})
}

nodejs: missing ) after argument list

When I run nodejs http_test.js, which is attached following, it appeared "missing ) after argument list", I check the "(" and "{" but felt nothing wrong. help!
const http = require('http');
http.get({
hostname: 'localhost',
port: 5000,
path: '/123/',
agent: false // create a new agent just for this one request
}, (res) => {
console.log(res)
// Do stuff with response
})
Per #aaron-dufour's comment above, you are probably trying to run that code in an interpreter that does not support ECMAScript 6.
If changing the contents of the file to the following works, then that's your problem:
var http = require('http');
http.get({
hostname: 'localhost',
port: 5000,
path: '/123/',
agent: false // create a new agent just for this one request
}, function(res) {
console.log(res)
// Do stuff with response
});
In your case, you are using Nodejs, which should be okay, given this article. It may be that you are using a significantly out of date version. Try running node -v or node --version to see what version you're running.

Hapijs getting started good good-console error reporter must specify events to filter on

I'm just starting to learn Hapijs
following getting started tutorial
with this example:
var Hapi = require('hapi');
var Good = require('good');
var server = new Hapi.Server();
server.connection({ port: 3000 });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: function (request, reply) {
reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
}
});
server.register({
register: Good,
options: {
reporters: [{
reporter: require('good-console'),
args:[{ log: '*', response: '*' }]
}]
}
}, function (err) {
if (err) {
throw err; // something bad happened loading the plugin
}
server.start(function () {
server.log('info', 'Server running at: ' + server.info.uri);
});
});
when I run
node server
I've got
/home/user/hapi/node_modules/good/node_modules/hoek/lib/index.js:683
throw new Error(msgs.join(' ') || 'Unknown error');
^
Error: reporter must specify events to filter on
Can you help me, please ?
The documentation is outdated. There were some breaking changes in good 6.0.0. The module good-console has a new version, however it is not published on npm yet. You can use the master branch though by specifying the GitHub repository in package.json:
"good-console": "hapijs/good-console"
You will also need to change the configuration to:
options: {
reporters: [{
reporter: require('good-console'),
events: {
response: '*',
log: '*'
}
}]
}
EDIT: Version 5.0.0 of good-console has been released. The documentation was also updated.

Resources