How to run Gun server with Hapi? - gun

I follow this tutorial to create Gun server. But I need to do it with Hapi.
Now, I get the following error:
> node server.js
Hello wonderful person! :) Thanks for using GUN, feel free to ask for help on https://gitter.im/amark/gun and ask StackOverflow questions tagged with 'gun'!
0.8 WARNING! Breaking changes, test that your app works before upgrading! The adapter interface has been upgraded (non-default storage and transport layers probably won't work). Also, `.path()` and `.not()` are outside core and now in 'lib/'.
WARNING! This `file.js` module for gun is intended for local development testing only!
/home/trex/dev/learn/gun/server/server.js:17
gun.wsp(server);
^
TypeError: gun.wsp is not a function
at Object.<anonymous> (/home/trex/dev/learn/gun/server/server.js:17:5)
Server source code:
const Hapi = require('hapi');
const Gun = require('gun');
const gun = new Gun();
const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });
server.ext('onRequest', () => gun.wsp.server);
gun.wsp(server);
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
What is wrong here?

The bug solved in gun 0.8.8 https://github.com/amark/gun/pull/423
const Hapi = require('hapi');
const Inert = require('inert');
const Gun = require('../gun/');
const server = new Hapi.Server;
server.connection({ port: 8080 });
server.connections.forEach(c => Gun({ web: c.listener, file: 'data.json' }));
server.register(Inert, () => {});
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: __dirname,
redirectToSlash: true,
index: true
}
}
});
server.start();

Related

Redis issue on module-redis-fork

Issue
Hi everyone,
I have an issue while trying to interact with Redis in those conditions:
Redis instance with Redisearch module,
Create node-redis client before Redis module fork is ongoing,
Redis module fork is on-going
The behaviour that I get is that "send_command" stays idle until the fork stops.
When the fork ends I get this error:
debug mode ->
Redis connection is gone from end event
client error ->
AbortError: Redis connection lost and command aborted. It might have been processed.
After I get this error the commands from the same client (without creating a new client) come back to works fine.
On every fork, I got the same behaviour.
Additional Info:
keys: 37773168,
used_memory_human: '87.31G'
Code Example:
This is a simple express app,
'use strict';
const express = require('express');
const Redis = require('redis');
// Redis.debug_mode = true;
const router = express.Router();
let client = null;
router.get('/redisearch/connect', async (req, res, next) => {
const conf = {
'host': '127.0.0.1',
'port': 6379,
'db': 0,
};
try {
if (!client) client = Redis.createClient(conf.port, conf.host, { db: conf.db });
res.send('Connected');
} catch (err) {
res.send(err);
}
});
router.get('/redisearch/d', async (req, res, next) => {
const num = 10;
const dArgs = ['testIndexName', `#ic:[${num} ${num}]`, 'GROUPBY', 1, '#d'];
try {
client.send_command('FT.AGGREGATE', dArgs, (err, reply) => {
if (err) {
res.send({ err: err });
};
res.send({ d: reply });
});
} catch (err) {
res.send(err);
}
});
module.exports = router;
this is the simplest way I have to replicate the problem.
I don't know if there is a way to force redis to use the fork, in my case it appears following a massive search on index followed by delete and insert of records.
Redis however during these operations (insert/delete) works normally,
I can launch commands from the redis-cli;
By creating a new instance of the node-redis client while the fork is present everything works normally and when the fork goes away everything keep working.
Environment
Node.js Version: v14.15.1
Redis Version: 6.0.4
redisearch Version: 1.6.15
node-redis Version: 3.2
Platform: Server 128GB RAM, 8 Core, Debian

502 Bad Gateway in Kubernetes cluster after I added mongoDB connection code

I was chugging along with my Kubernetes cluster project when after creating a User model to start creating users in my application, I get a 502 Bad Gateway error in my Postman client.
So I was so focused on my ingress-nginx yaml file, staring at it for typos, rewriting it, uninstalling, reinstalling and still getting that error, that I decided to take it the next step further.
Via the current user route handler:
import express from "express";
const router = express.Router();
router.get("/api/users/currentuser", (req, res) => {
res.send("howdy!");
});
export { router as currentUserRouter };
I have always been able to go to my browser and successfully see howdy! rendered when I went to mywebsite.com/api/users/currentuser
but then I added some logic to index.ts file I did not particular care for from the https://expressjs.com/en/guide/routing.html:
app.all("*", async (req, res) => {
throw new NotFoundError();
});
Well, sure enough that killed my ability to go to mywebsite.com/api/users/currentuser and see howdy! rendered and instead I was getting a 502 Bad Gateway. So I said okay I will just leave that one out then.
But then I noticed a huge chunk of very important code was breaking my ability to visit that url as well:
// const start = async () => {
// try {
// await mongooose.connect("mongodb://auth-mongo-srv:27017/auth", {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// useCreateIndex: true,
// });
// console.log("Connected to MongoDB");
// } catch (error) {
// app.listen(3000, () => {
// console.log("Listening on port 3000!!!!!");
// });
// }
// };
// start();
All of the above is what I need to connect to my local MongoDB server and start creating users.
So I started to even get more granular and slowly commenting code back in. Well, the app.all() is not a problem anymore, the problem seems to be throwing my mongoDB connection code inside of a try/catch statement, but I have no idea why that would have created the problem. Any ideas anyone?
So instead if I just run it like this:
const start = async () => {
await mongooose.connect("mongodb://auth-mongo-srv:27017/auth", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
console.log("Connected to MongoDB");
app.listen(3000, () => {
console.log("Listening on port 3000!!!!!");
});
};
start();
It all works fine again.

Better way for gulp task to wait for express server to start

Need gulp 4.0.2 task to wait for express 4.17.1 server to start, then open a browser.
Here's what I have that works (but I think it's pretty old school)...
// Start server in development or test mode
gulp.task('start:server', () => {
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
config = require(`./${serverPath}/config/environment`).default;
nodemon(`--inspect --trace-deprecation --trace-warnings -w ${serverPath} ${serverPath}`)
.on('log', onServerLog);
});
// Run nodemon with debugging (server/config/express.js runs webpack.make.js)
gulp.task('serve',
gulp.series(
gulp.parallel('eslint', 'eslint:tests', 'client:inject:scss', 'dist:client:assets:fonts', 'env:common'),
gulp.parallel('start:server', 'start:client'),
'watch'
)
);
// Perform HTTP GET to check for app readiness
function checkAppReady(cb) {
let options = {
host: 'localhost',
port: config.port
};
http.get(options, () => cb(true))
.on('error', () => cb(false));
}
// Check every 250ms until app server is ready
function whenServerReady(cb) {
let serverReady = false;
let appReadyInterval = setInterval(() =>
checkAppReady(ready => {
if(!ready || serverReady) {
return;
}
clearInterval(appReadyInterval);
serverReady = true;
cb();
}),
250);
}
// Wait until server is responding then open browser on client to our starting page
gulp.task('start:client', done => {
whenServerReady(() => {
opn(`http://localhost:${config.browserSyncPort}`/*, {app: 'google chrome'}*/);
done();
});
});
While this works well, I'm wondering if there's a more streamlined way to accomplish the same thing. The last StackOverflow post on the subject is more than 3 years old.

error hanlders not working properly in express together with nuxtjs

I am using Nuxtjs as a middleware in expressjs, and I have problems with handling errors in express server part.
When browser goes to 'localhost:3000', it will throw res.status is not a function error. when I comment that code block, everything is good expect that I cannot handle with uncaught server errors...
Any ideas?
import dotenv from 'dotenv'
dotenv.config({ silent: process.env.NODE_ENV === 'production', path: 'server/.env' })
import express from 'express'
import { ready } from 'consola'
import { Nuxt, Builder } from 'nuxt'
import cors from 'cors'
import { json, urlencoded } from 'body-parser'
import cookieParser from 'cookie-parser'
import passport from 'passport'
import './utils/auth'
import router from './routes'
const app = express()
app.use(json({ limit: '50mb' }))
app.use(urlencoded({ limit: '50mb', extended: true }))
app.use(cookieParser())
app.use(cors())
app.use(passport.initialize())
app.use('/api', router)
app.use('/api/*', (req, res) => {
res.status(404).end()
})
// error handlers
// it is problematic
// app.use((err, req, res) => {
// res.status(err.status || 500).end()
// })
let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
const nuxt = new Nuxt(config)
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
app.use(nuxt.render)
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000
app.set('port', port)
app.listen(port, host)
ready({
message: `Server listening on http://${host}:${port}`,
badge: true,
})
}
start()
Without testing this code myself, I had a similar issue with my custom error handler and realized at one point I removed the next argument and it was failing. Can't say it will fix the issue because you are getting an error about res. I read through this page a few times and noticed a few mistakes I was making because I was using async functions.
Error Handling Guide may provide some help if you look over it carefully, but more specifically my comment about next is found under the title Writing error handlers
I wanted to say it might be arrow functions, but I don't see why that would break the logic here.

Neutrino and Express Preset

I'm using Neutrino as scaffolding tool for Webpack 3.1 and I'm looking for a proper Neutrino preset that combines Express and Webpack so that I see a 'Hello World' website. If someone gives me one proper preset and tells me how to install it, I'll accept this as an answer.
Thank you!
This should already be possible with the #neutrinojs/node preset:
// src/index.js
import express from 'express';
import { join } from 'path';
const port = process.env.PORT || 3000;
const app = express();
app.get('/', (request, response) => {
response.sendFile(join(__dirname, 'index.html'));
});
app.listen(port, () => console.log(`Server running on port ${port}`));