I'm trying to use fatify swagger in my fastify app and I was unable to start the application with the fastify swagger. i was getting the error. Please help me in resolving the error. Thanks in advance.
This is the error I'm getting when I'm running the app
fastify_app#1.0.0 start D:\dev\fastify_app
node app.js
{"level":30,"time":1666146720089,"pid":13484,"hostname":"Dell","msg":"Server listening at http://127.0.0.1:3000"}
{"level":30,"time":1666146720113,"pid":13484,"hostname":"Dell","msg":"Server listening at http://[::1]:3000"}
D:\dev\fastify_app\app.js:15
fastify.swagger()
^
TypeError: fastify.swagger is not a function
at D:\dev\fastify_app\app.js:15:15
at D:\dev\fastify_app\node_modules\fastify\lib\server.js:67:11
at Object.cb (D:\dev\fastify_app\node_modules\fastify\lib\server.js:128:15)
at Server.wrap (D:\dev\fastify_app\node_modules\fastify\lib\server.js:166:21)
at Object.onceWrapper (events.js:519:28)
at Server.emit (events.js:400:28)
at emitListeningNT (net.js:1365:10)
at processTicksAndRejections (internal/process/task_queues.js:81:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fastify_app#1.0.0 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the fastify_app#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Dell\AppData\Roaming\npm-cache\_logs\2022-10-19T02_32_00_228Z-debug.log
This is my swagger.js file
const fastify = require("fastify")();
exports.options = fastify.register(require("#fastify/swagger"), {
routePrefix: "/docs",
exposeRoute: true,
swagger: {
info: {
title: "Fastify API",
description:
"Building a blazing fast REST API with Node.js, MongoDB, Fastify and Swagger",
version: "1.0.0",
},
externalDocs: {
url: "https://swagger.io",
description: "Find more info here",
},
host: "localhost:3000",
schemes: ["http"],
consumes: ["application/json"],
produces: ["application/json"],
},
});
This is my app.js code
const fastify = require("fastify")({logger:true});
require("dotenv").config();
const PORT = process.env.PORT;
fastify.register(require("./app/Routes/users.route"));
const swagger = require('./swagger')
fastify.get("/", (req, res) => {
res.send("Hello world");
});
const start = async () => {
try {
await fastify.listen({ port: PORT }, () => {
fastify.swagger()
console.log(`server is listening on port ${PORT}`);
});
} catch (error) {
console.log(error);
process.exit(1);
}
};
start();
Related
I am building a fastify application with mongodb. I've created this package.json file with a script to run mongo.
{
"dependencies": {
"#fastify/mongodb": "5.0.0",
"fastify": "4.11.0"
},
"scripts": {
"start": "node server.js",
"start-mongo": "docker run -d --name my-mongo -p 27017:27017 mongo",
}
}
And with npm run start-mongo I run mongo exposing port 27017. Then, ... this is fastify part.
const fastify = require('fastify')({logger: true})
fastify.register(require('#fastify/mongodb'), {
forceClose: true,
url: 'mongodb://localhost:27017/library'
})
fastify.get('/books', async(request, reply) => {
const books = await fastify.mongo.db
.collection('books')
.find()
reply.send(books)
});
fastify.post('/books', async(request, reply) => {
const result = await fastify
.mongo.db
.collection('books')
.insertOne(request.body)
reply.send({
message: 'book added',
id: result.insertId
})
})
GET /books:
{"_events":{},"_eventsCount":0}
POST /books
curl -H 'Content-Type: application/json' -X POST http://localhost:3000/books -d '{"message":"prova"}'
returns
{"message":"book added"}
It is strange because response should contain also id. But it doesnt.
reply.send({
message: 'book added',
id: result.insertId
})
This means that
const result = await fastify
.mongo.db
.collection('books')
.insertOne(request.body)
doesnt store the book. Any error is displayed and GET always return:
{"_events":{},"_eventsCount":0}
What's wrong?
--
I've also created mongo with docker-compose:
version: '3.1'
services:
mongo:
image: mongo
restart: always
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
but it returns:
{
statusCode: 500,
code: '13',
error: 'Internal Server Error',
message: 'command insert requires authentication'
}
{
statusCode: 500,
code: '13',
error: 'Internal Server Error',
message: 'command find requires authentication'
}
I updated code from
fastify.register(require('#fastify/mongodb'), {
forceClose: true,
url: 'mongodb://localhost:27017/library'
})
to
fastify.register(require('#fastify/mongodb'), {
forceClose: true,
url: 'mongodb://root:example#localhost:27017/library'
})
but returns:
(node:86146) UnhandledPromiseRejectionWarning: MongoServerError: Authentication failed.
at Connection.onMessage (/Users/simonegentili/Development/github.com/sensorario/youtube.poliglotta/node_modules/mongodb/lib/cmap/connection.js:227:30)
at MessageStream.<anonymous> (/Users/simonegentili/Development/github.com/sensorario/youtube.poliglotta/node_modules/mongodb/lib/cmap/connection.js:60:60)
at MessageStream.emit (events.js:375:28)
at processIncomingData (/Users/simonegentili/Development/github.com/sensorario/youtube.poliglotta/node_modules/mongodb/lib/cmap/message_stream.js:125:16)
at MessageStream._write (/Users/simonegentili/Development/github.com/sensorario/youtube.poliglotta/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at Socket.ondata (internal/streams/readable.js:726:22)
at Socket.emit (events.js:375:28)
at addChunk (internal/streams/readable.js:290:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:86146) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:86146) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Why "Authentication failed"?
You need to:
update fastify mongo to v6 that supports fastify v4
The GET returns a cursor so change it to fastify.mongo.db.collection('books').find().toArray()
To get back the inserted id you need to change from inserted to insertedId
to set the MongoDB password duplicated question or you need to set the database property - code below updated:
note the plugin configuration
note the usage fastify.mongo.db.collection
Quick and dirty copy-paste:
const fastify = require('fastify')({ logger: !true })
fastify.register(require('#fastify/mongodb'), {
forceClose: true,
url: 'mongodb://root:example#localhost:27017',
database: 'library'
})
fastify.get('/books', async (request, reply) => {
const books = await fastify.mongo.db.collection('books').find().toArray()
reply.send(books)
})
fastify.post('/books', async (request, reply) => {
const result = await fastify
.mongo.db
.collection('books')
.insertOne(request.body)
reply.send({
message: 'book added',
id: result.insertedId
})
})
async function start () {
const done = await fastify.inject({
method: 'POST',
url: '/books',
body: { asd: 'foo' }
})
console.log(done.json())
const res = await fastify.inject('/books')
console.log(res.json())
fastify.close()
}
start()
I'm trying to connect in to my DATA Base using Mongoose here is my code:
mongoose
.connect(process.env.MONGODB_URL)
.then(() => {
console.log("connected to MongoDB!");
})
.catch((err) => {
console.log(err);
});
Expecting from console.log( "connected to MongoDB!"); but instead i get this :
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
server started by me
/subscribers
Error: querySrv ETIMEOUT _mongodb._tcp.subscribers-app.nrro0mj.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:251:17) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'querySrv',
hostname: '_mongodb._tcp.subscribers-app.nrro0mj.mongodb.net'
}
The problem was in my router
solutions:
Restart your Router.
Manually Set your DNS Server.
I was able to run my Protractor tests using browserstack-local earlier tonight but was unable to by the end of the evening and I can't figure out what's going on.
node v7.4.0
protractor v5.0.0
browserstack-local v1.2.0
Here's my conf.ts file:
'use strict';
import { Config, browser } from 'protractor';
import testSuites = require('./testSuites.js');
import browserstack = require('browserstack-local');
const commonCapabilities = {
'browserstack.user': '*****',
'browserstack.key': '*****',
'browserstack.local': true
};
export let config: Config = {
baseUrl: 'https://localhost:8443',
seleniumAddress: 'http://hub-cloud.browserstack.com/wd/hub',
multiCapabilities: [{
browserName: 'chrome',
browser_version: '54.0',
os: 'Windows',
os_version: '10',
resolution: '1280x800'
}],
specs: ['src/**/*spec.js'],
suites: testSuites.suites,
framework: 'mocha',
mochaOpts: {
reporter: 'spec',
slow: 0,
timeout: 60000
},
allScriptsTimeout: 3600000,
onPrepare: () => {
browser.manage().window().setSize(1280, 800);
},
params: {
user: 'seleniumtesting'
},
beforeLaunch() {
console.log('Starting BrowserStack Local...');
return new Promise((resolve, reject) => {
exports.bs_local = new browserstack.Local();
exports.bs_local.start({ key: commonCapabilities['browserstack.key']}, error => {
if (error) {
return reject(error);
}
console.log('BrowserStack Started.');
resolve();
});
});
},
afterLaunch() {
return new Promise(resolve => {
if (!exports.bs_local) {
console.log('Skipping shutdown of BrowserStack Local...');
resolve();
return;
}
console.log('Stopping BrowserStack Local...');
exports.bs_local.stop(resolve);
});
}
};
// Code to support common capabilities
exports.config.multiCapabilities.forEach((caps) => {
Object.keys(commonCapabilities).forEach(i => {
caps[i] = caps[i] || commonCapabilities[i];
});
});
When I run my Protractor tests I'm getting:
Starting BrowserStack Local...
(node:3755) DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
/usr/local/lib/node_modules/protractor/node_modules/q/q.js:155
throw e;
^
Error
at /protractor/node_modules/browserstack-local/lib/Local.js:57:20
at ChildProcess.exithandler (child_process.js:202:7)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:885:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:501:12)
It's strange because I didn't change anything in my environment since it was last working earlier in the evening, and now I can't get it to run anymore without seeing this error. I've been trying to debug this without any luck, could someone please help me spot if I'm missing anything?
Thanks in advance!
"os.tmpDir" deprecated onwards Node v7.0.0. Try downgrading your Node and execute.
More details are available in https://github.com/hapijs/hapi/issues/3369
I have a Mongo db setup on localhost:27017 and and trying to connect to it from my app that uses Webpack via Mongoose. I have Mongoose installed as a package. Here is my code:
import mongoose from 'mongoose';
var db = mongoose.connect('mongodb://localhost:27017/music-app');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
I'm pretty sure i've followed the documentation correctly but it's throwing the following compile error:
Error in ./~/mongoose/~/mongodb/~/mongodb-core/~/require_optional/~/resolve-from/index.js
Module not found: 'module' in C:\Users\new\Desktop\Development Projects\music-app\node_modules\mongoose\node_modules\mongodb\node_modules\mongodb-core\node_modules\require_optional\node_modules\resolve-from
There is also another error in the console:
webpackHotDevClient.js:216 Error in ./~/mongoose/~/mongodb/lib/mongo_client.js
Module not found: 'dns' in C:\Users\new\Desktop\Development Projects\music-app\node_modules\mongoose\node_modules\mongodb\lib
# ./~/mongoose/~/mongodb/lib/mongo_client.js 12:10-24
Anyone seen this before and know how to resolve it? Is there additional packages I might need to install in node?
This error is because you're trying to use mongodb from browser, as create-react-app is a front-end app.
You should use a back-end server and use mongodb from there.
You can check out this this full-stack repo having a nodejs server with create-react-app front-end.
https://github.com/fullstackreact/food-lookup-demo
That is because Webpack can’t statically analyze if (typeof window === 'undefined') in mongoose/lib/drivers/index.js
Here is the solution:
webpackConfig.plugins = [
...,
new webpack.DefinePlugin({
'typeof window': "\"object\""
}),
...
]
Also, if you get error messages regarding mongoose, check out below configurations.
npm install node-loader --save-dev
npm install require_optional --save-dev
npm install module --save-dev
webpack.config.js
const webpackConfig = {
name : 'client',
target : 'web',
devtool : config.compiler_devtool,
resolve : {
root : paths.client(),
extensions : ['', '.js', '.jsx', '.json', '.coffee', '.node']
},
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
},
module : {}
}
// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
test : /\.(js|jsx)$/,
exclude : /node_modules\/(?!(lodash-es)\/).*/,
loader : 'babel',
query : config.compiler_babel
}, {
test : /\.json$/,
loader : 'json'
}, {
test: /\.coffee$/,
loader: 'coffee-loader',
exclude: /node_modules|lib/
}, {
test: /\.node$/,
loader: 'node-loader'
}]
I am trying to set up some async tests using karma and jasmine. I am clearly making a very stupid mistake but I need it pointing out to me. After simplifying as much as possible I have the following:
package.json
{
"name": "newtest",
"version": "0.0.0",
"scripts": {
"test": "karma start karma.conf.js"
},
"devDependencies": {
"karma": "^0.12.28",
"karma-chrome-launcher": "^0.1.5",
"karma-jasmine": "^0.2"
}
}
karma.conf.js
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'tests/**/*.js'
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: true
});
};
tests/dummy.spec.js
describe("Testing async", function() {
it('should fail this test', function(done) {
setTimeout(function(){
expect(1).toBe(2);
done();
}, 1000);
});
it('should not fail this test', function(done) {
done();
});
});
and I am getting the following:
npm test
> newtest#0.0.0 test /home/mark/Projects/newtest
> karma start karma.conf.js
INFO [karma]: Karma v0.12.16 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 39.0.2171 (Linux)]: Connected on socket T7j6LvNAwvS89wUdymCb with id 16891024
Chrome 39.0.2171 (Linux) Testing async should not fail this test FAILED
TypeError: undefined is not a function
at null.<anonymous> (/home/mark/Projects/newtest/tests/dummy.spec.js:12:5)
Chrome 39.0.2171 (Linux): Executed 2 of 2 (1 FAILED) (0.007 secs / 0.005 secs)
npm ERR! Test failed. See above for more details.
npm ERR! not ok code 0
So the test that I think should fail is passing fine, and vice-versa. Can someone point me to my error(s)?
I guess the first one fail because when the timeout is reach the test is allready finish, so both doesn't work.
It's has you'r not using jasmine 2.
The syntax seems good to me, what I can tell you is the difference with my configuration (wich is working) :
I have put karma-jasmine in dependencies with a ~ :
"dependencies": {
...
"karma-jasmine": "~0.2.0"
},
I'm using PhantomJS :
browsers:['PhantomJS'],
I don't know why I am having the problem, but I have tried on another machine and it works as expected.