Cannot set uncompiled validation rules without configuring a validator - node.js

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()
})
}

Related

How to move an #hapi plugin out to its own separate file

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.

Apollo Server Express - Playground cannot be reached

I am trying to follow this tutorial https://www.youtube.com/watch?v=I6ypD7qv3Z8&t=48972s but I am stuck on trying to make the playground work.
I get to the playground on "http://localhost:4000/graphql" but somehow I get the "Server cannot be reached" error. In the network inspector I see "Cannot POST /" 404s.
Here's my code (app.ts):
import { ApolloServer } from "apollo-server-express";
import { ApolloServerPluginLandingPageGraphQLPlayground } from "apollo-server-core";
import { buildSchema } from "type-graphql";
import { PORT } from "./constants";
import { HelloResolver } from "./graphql/resolvers";
export const main = async () => {
const app = express();
const apolloServer = new ApolloServer({
schema: await buildSchema({ resolvers: [HelloResolver], validate: false }),
plugins: [ApolloServerPluginLandingPageGraphQLPlayground],
});
await apolloServer.start();
apolloServer.applyMiddleware({ app });
app.listen(PORT, () => {
console.log(
`Server started on http://localhost:${PORT}${apolloServer.graphqlPath}`
);
});
};
Things I did extra from the tut:
Made PORT a variable with value 4000
Added the "ApolloServerPluginLandingPageGraphQLPlayground" for the old school playground (newest doesn't work either)
Added the "await apolloServer.start();" line as specified on the doc, I get an error if I don't
Things I tried:
Using the http server stuff from the doc (https://www.apollographql.com/docs/apollo-server/integrations/middleware/#apollo-server-express) -> same issue
Any idea on where could be the issue? Seems like express didn't create the POST endpoint for the /graphql route.
EDIT: It works if I change this:
apolloServer.applyMiddleware({ app });
to this:
apolloServer.applyMiddleware({ app, path: "/" });
I found the answer here! helpful. Do check it out!
Try using 127.0.0.1 instead of localhost. It worked for me. Also If you have cached queries and mutations that you still want to use, switching back to localhost from 127.0.0.1 will have the localhost working again.
I recently had this issue too. This was the case where the
Server cannot be reached/no visible schema but still able to execute a query
To fix this you should have this as in your ApolloServer initializer:
const server = new ApolloServer({
csrfPrevention: true,
plugins: [
ApolloServerPluginLandingPageGraphQLPlayground(),
],
instrospection: true,
})
Read more about instrospection here and this github issue.

Connection to postgresql db from node js

I'm tyring to make a connection from my nodejs script to my db connection, but seems like there is a suspicius issue i'm not able to figure out.
At the moment, this is my code:
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: '192.168.1.xxx',
database: 'database',
password: 'password',
port: 5432,
});
pool.on('error', (err, client) => {
console.error('Error:', err);
});
const query = `SELECT * FROM users`;
pool.connect()
.then((client) => {
client.query(query)
.then(res => {
for (let row of res.rows) {
console.log(row);
}
})
.catch(err => {
console.error(err);
});
})
.catch(err => {
console.error(err);
});
The issue seems to be in pool.connect(), but i can't understand what i'm missing because i got no errors in the log. I've installed pg module in the directory of my project with npm install --prefix pg and i know modules are loaded correctly.
I edited postgresql.conf:
# - Connection Settings -
listen_addresses = '*'
and pg_hba.conf
host database user 192.168.1.0/24 md5
to make the database reachable via lan and seems liek it works, because i'm able to connect successfully with apps like DBeaver...but i can't with NodeJS.
It's possible there is some kind of configuration i've to active?

Getting error UnhandledPromiseRejectionWarning

Trying to run a sftp client using nodejs but getting a wired error. The error is
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
let Client = require('ssh2-sftp-client');
let sftp = new Client();
const process = require('process');
const config = {
host: 'localhost',
port: '1026',
username: 'Nav****',
password: '*******'
}
sftp.connect(config)
const list = ()=>{
sftp.connect(config).then(() => {
return sftp.list('../send_backend');
}).then((data) => {
console.log(data, 'the data info');
}).catch((err) => {
console.log(err, 'catch error');
})
}
console.log("=======================================");
console.log("received data =>" + list());
What is "sftp.connect(config)" doing outside the list. As I can see you are neither using resolve nor the rejected case. That is causing the issue. So you should either handle the exception or remove that code!
In case you want to handle it
sftp.connect(config)
.then(()=>{//do something here})
.catch((exception)=>{ console.log(exception) // do something else })
As discussed in comments, You may use this:
let Client = require('ssh2-sftp-client');
let sftp = new Client();
const process = require('process');
const config = {
host: 'localhost',
port: '1026',
username: 'Nav****',
password: '*******'
}
sftp.connect(config)
.then(()=>{
// what you want to do after you make connection goes here
})
.catch((exception)=>{
console.log(exception) // do something else
})

Node-Redis: ready check failed - NOAUTH Authentication required

I have a strange redis behavior:
const redis = require('redis');
const { REDIS_URL: redisUrl, REDIS_PASSWORD: redisPassword } = process.env;
const client = redis.createClient(redisUrl, {
no_ready_check: true,
auth_pass: redisPassword
});
client.on('connect', () => {
redisPassword && client.auth(redisPassword);
});
client.on('error', err => {
global.console.log(err.message)
});
But all the time I receive following error:
throw er; // Unhandled 'error' event
ReplyError: Ready check failed: NOAUTH Authentication required.
Why unhandled ? I set onerror handler
Why Ready check failed ? I disabled it in options
I'm not sure why your code will throw this error. But I try this code in my local machine, it works well.
const redis = require('redis');
const redisPassword = "password" ;
const client = redis.createClient({
host : '127.0.0.1',
no_ready_check: true,
auth_pass: redisPassword,
});
client.on('connect', () => {
global.console.log("connected");
});
client.on('error', err => {
global.console.log(err.message)
});
client.set("foo", 'bar');
client.get("foo", function (err, reply) {
global.console.log(reply.toString())
})
And run node client.js will output :
connected
bar
NOAUTH Authentication required is caused by when redis process command , it found the client is not authenticated so it complained with it.
I guess maybe the redisUrl you give to createClient has some problem, try to debug it or change to my code's way to try. Hopefully you can fix it.
And one more thing: the client.auth(redisPassword) is not necessary because if you set an auth_pass or password option, the redis client will auto send auth command to server before any command.
If you have redis uri saved as string. You need decompose it to object. For ioredis you can use function
export function decomposeRedisUrl(url) {
const [[, , password, host, port]] = [...(url.matchAll(/redis:\/\/(([^#]*)#)?(.*?):(\d*)/g))];
return { password, host, port };
}
There are tests for this function:
it("redis url should be decomposed correctly with password", () => {
expect(decomposeRedisUrl("redis://pass#host.com:9183")).to.eql({
password: "pass",
host: "host.com",
port: "9183",
});
});
it("redis url should be decomposed correctly without password", () => {
expect(decomposeRedisUrl("redis://localhost:6379")).to.eql({
password: undefined,
host: "localhost",
port: "6379",
});
});
and usage
import Redis from "ioredis";
async function getKeysFromRedisUrl(url) {
const rc = new Redis(decomposeRedisUrl(url));
const keys = await rc.keys("*");
rc.disconnect();
return keys;
}
describe("Redis can connect", () => {
it("with cloud", async () => {
expect(await getKeysFromRedisUrl("redis://pass#host.com:9183")).to.be.an("array");
});
it("with local redis instance", async () => {
expect(await getKeysFromRedisUrl("redis://localhost:6379")).to.be.an("array");
});
});
user name is not handled in this function
if you're using docker to run Redis, check if your docker-compose has the command: redis-server --requirepass redis
Then check your .env file to make sure you're using it.
It was the problem here and I was able to fix it by adding the password at .env file.

Resources