While trying to use the fastify-passport plugin as per documented on the npm documentation i am getting the beloe error while the application is initializing:
server.register(fastifypassport.initialize());
^
TypeError: fastifypassport.initialize is not a function
my index.js looks as below:
'use strict'
import fastify from 'fastify'
import fasifyPassport from 'fastify-passport'
import fastifySecureSession from 'fastify-secure-session'
import loginController from './controller/loginController.js';
import { readFileSync } from 'fs';
import { join } from 'path';
const server = fastify({
logger: true
})
// set up secure sessions for fastify-passport to store data in
server.register(fastifySecureSession, { key: readFileSync(join("", "secret-key")) });
// initialize fastify-passport and connect it to the secure-session storage. Note: both of these plugins are mandatory.
server.register(fasifyPassport.initialize());
server.register(fasifyPassport.secureSession());
server.listen(3000, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
server.log.info(`server listening on ${address}`)
})
Have tried a couple of options like import of the function in {} as well but that also did not work.. Any help would be highly appreciated...
Related
I want to make a socket.io server using NestJS.
I'm trying communication between server and client on localhost.
however, client(socket.io-client) throw the following error.
TransportError: xhr poll error
the server was running on localhost:3000. and the client was run from node command(node index.js)
server (mock.gateway.ts)
import { SubscribeMessage, WebSocketGateway, MessageBody, ConnectedSocket, WebSocketServer} from '#nestjs/websockets';
import { Socket } from 'socket.io';
#WebSocketGateway()
export class MockGateway {
#WebSocketServer()
server;
#SubscribeMessage('mock')
mock(
#MessageBody() data: string,
#ConnectedSocket() socket: Socket
): void {
console.log(data);
}
}
server (main.ts)
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
client
import { io, Socket } from 'socket.io-client';
const socket = io('ws://localhost:3000', {
path: '/socket.io',
});
socket.emit('mock', 'mock');
I tried set transports to the sockect.io-client. but it makes a timeout error.
import { io, Socket } from 'socket.io-client';
const socket = io('ws://localhost:3000', {
path: '/socket.io',
transports: ['websocket'],
});
socket.emit('mock', 'mock');
Maybe a mistake in module settings. so I use the wscat is debug-tool. It throws the following error, I'm wondering why wscat can connest Nest server.
$ wscat -c ws://localhost:3000/socket.io/\?transport=websocket
Connected (press CTRL+C to quit)
error: Invalid WebSocket frame: RSV1 must be clear
If anyone has any ideas, please comment.
I am struggling with binding IPFS node with NestJS instance on the server. All was working fine on the local machine, but on the server, I have a working instance of the IPFS. I know that it works as I can see connected peers and I can see a file uploaded through the server console by https://ipfs.io/ipfs gateway.
The code of the IPFS service is quite simple and it does not produce any errors until I try to upload something.
import { Injectable } from '#nestjs/common';
import { create } from 'ipfs-http-client';
#Injectable()
export class IPFSClientService {
private client = create({
protocol: 'http',
port: 5001
});
public async upload(file: Express.Multer.File): Promise<string> {
const fileToAdd = { path: file.filename, content: file.buffer };
try {
const addedFile = await this.client.add(fileToAdd, { pin: true });
return addedFile.path;
} catch (err) {
console.log('err', err);
}
}
}
Unfortunatelly the error message is enigmatic.
AbortController is not defined
at Client.fetch (/home/xxx_secret/node_modules/ipfs-utils/src/http.js:124:29)
at Client.fetch (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/lib/core.js:141:20)
at Client.post (/home/xxx_secret/node_modules/ipfs-utils/src/http.js:171:17)
at addAll (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/add-all.js:22:27)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at Object.last [as default] (/home/xxx_secret/node_modules/it-last/index.js:13:20)
at Object.add (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/add.js:18:14)
at IPFSClientService.upload (/home/xxx_secret/src/ipfs/ipfs-client.service.ts:20:25)
I will appreciate any help in this matter as I don't have ideas regarding this issue :/
I am very new to NestJs and I would like to build a web app that uses MongoDB.
So what I gonna do is whenever as soon as app is loading mongodb connection should be made and add some logic in callback function.
With Express framework this is the code of logic what I wanna do.
mongoose
.connect(mongoDB, {
user: process.env.MONGODB_USER,
pass: process.env.MONGODB_PASSWORD,
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(async () => {
//don't show the log when it is test
if (process.env.NODE_ENV !== "test") {
console.log("Connected to %s", mongoDB);
console.log("MongoDB is connected ... \n");
initDB.InitializeDB();
dailyReport.DailyReport();
}
})
.catch((err) => {
console.error("App starting error:", err.message);
process.exit(1);
});
In above code there are two functions.
1st: Logging if DB connection is successful or failed
2nd: When successful I initialize some collections and exit app if failed
I saw NestJs documentation to implement this logic here
import { Module } from '#nestjs/common';
import { MongooseModule } from '#nestjs/mongoose';
#Module({
imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
})
export class AppModule {}
But I am not sure where is the callback function for MongoDB connection.
Can anyone give me answer for this by implementing Express logic using NestJs?
You could do the initialization in the onModuleInit() lifecycle method. Check here for more information: https://docs.nestjs.com/fundamentals/lifecycle-events#lifecycle-events
Code would look like this:
#Module({
imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
})
export class AppModule {
#InjectConnection() private connection: Connection;
onModuleInit() {
// execute logic + access mongoDB via this.connection
}
}
I'm trying to use Fastify with my project, but when I want to start the server, it isn't opening the specific port.
I'm creating the server like this:
import { NestFactory } from "#nestjs/core";
import { NestFastifyApplication, FastifyAdapter } from "#nestjs/platform-fastify";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter()
);
await app.listen(3000, '0.0.0.0');
}
bootstrap();
It says the application is successfully started, but when I check with netstat -ano,
the address(0.0.0.0:3000) isn't there.
The server logs:
I'm trying to use the redis module to look up a key value in a redis table. However, the very import itself (import redis from 'redis') is throwing the following error:
Failed to compile.
./node_modules/bindings/bindings.js Module not found: Can't resolve
'fs' in '/home/ubuntu/proost/web/node_modules/bindings'
Build error occurred Error: > Build failed because of webpack errors
at build (/home/ubuntu/proost/web/node_modules/next/dist/build/index.js:6:847)
error Command failed with exit code 1.
I tried reading up the module's documentation but couldn't find any reference to this issue. For what it's worth, my next.config.js file (a custom NextJS extension of Webpack) looks like this:
/* eslint-disable no-unused-vars */
import path from 'path';
import glob from 'glob';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import webpack from 'webpack';
import dotenv from 'dotenv';
import OptimizeCSSAssetsPlugin from 'optimize-css-assets-webpack-plugin';
import withSass from '#zeit/next-sass';
import withCSS from '#zeit/next-css';
import withPurgeCss from 'next-purgecss';
// dotenv.config();
const { parsed: localEnv } = dotenv.config();
module.exports = withCSS(withSass(withPurgeCss({
distDir: '.build',
purgeCssPaths: [
'pages/**/*',
'components/**/*',
],
webpack: (config, { dev, isServer }) => {
if (isServer) {
return config;
}
config.plugins.push(
new webpack.DefinePlugin({
'process.env': {
BASE_URL: JSON.stringify(process.env.BASE_URL),
REDIS_HOST: JSON.stringify(process.env.REDIS_HOST),
REDIS_PORT: JSON.stringify(process.env.REDIS_PORT),
},
}),
new webpack.EnvironmentPlugin(localEnv),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
);
config.optimization.minimizer.push(
new OptimizeCSSAssetsPlugin({}),
);
return config;
},
})));
Any way to fix this problem?
Seems to me you're trying to build a JS bundle with Webpack which should be used in browser's JS. But you can't use that redis package for browser's JS, it's only to be run in Node.js.