Nest automatically populates the graphql.options.ts with unknown schema - nestjs

I just followed the documentation and attached prisma to my nest project. The problem is, when I run yarn start:dev it populates the graphql.options.ts with some unknown schema and throws the following error:
[nodemon] starting `ts-node -r tsconfig-paths/register src/main.ts`
[Nest] 50392 - 12/24/2018, 10:08:57 PM [NestFactory] Starting Nest application...
[Nest] 50392 - 12/24/2018, 10:08:57 PM [InstanceLoader] AppModule dependencies initialized +43ms
[Nest] 50392 - 12/24/2018, 10:08:57 PM [InstanceLoader] PrismaModule dependencies initialized +0ms
[Nest] 50392 - 12/24/2018, 10:08:57 PM [InstanceLoader] UsersModule dependencies initialized +1ms
[Nest] 50392 - 12/24/2018, 10:08:57 PM [InstanceLoader] GraphQLModule dependencies initialized +0ms
(node:50392) UnhandledPromiseRejectionWarning: Error: Interface field Vehicle.wheels expects type Int but Car.wheels is type String.
Interface field argument Vehicle.stuff(a:) expects type Int but Car.stuff(a:) is type String.
at assertValidSchema (/Users/pubudu/Projects/nest-prisma-sample/node_modules/graphql/type/validate.js:71:11)
at assertValidExecutionArguments (/Users/pubudu/Projects/nest-prisma-sample/node_modules/graphql/execution/execute.js:146:35)
at executeImpl (/Users/pubudu/Projects/nest-prisma-sample/node_modules/graphql/execution/execute.js:67:3)
at Object.execute (/Users/pubudu/Projects/nest-prisma-sample/node_modules/graphql/execution/execute.js:62:229)
at Object.generateSchemaHash (/Users/pubudu/Projects/nest-prisma-sample/node_modules/apollo-server-core/src/utils/schemaHash.ts:11:18)
at new ApolloServerBase (/Users/pubudu/Projects/nest-prisma-sample/node_modules/apollo-server-core/src/ApolloServer.ts:299:23)
at new ApolloServer (/Users/pubudu/Projects/nest-prisma-sample/node_modules/apollo-server-express/src/ApolloServer.ts:70:1)
at GraphQLModule.<anonymous> (/Users/pubudu/Projects/nest-prisma-sample/node_modules/#nestjs/graphql/dist/graphql.module.js:118:33)
at Generator.next (<anonymous>)
at fulfilled (/Users/pubudu/Projects/nest-prisma-sample/node_modules/#nestjs/graphql/dist/graphql.module.js:16:58)
(node:50392) 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)
(node:50392) [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.
Here's the sample code:
https://github.com/THPubs/nest-prisma-sample
Any idea what's happening?

The issues is with the GraphQLOptions. In there, according to the examples, I have defined the typePaths as follows:
typePaths: ['./**/*.graphql'],
It looks like this gets all the graphql files in the project even from the node_modules folder. So, to import exactly the file I want, I used the following:
typePaths: ['./src/prisma/prisma-types.graphql'],

Related

(node:1928) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.createIndex()` buffering timed out

Getting the following error when I tried to estalish connection to my MongoDB Atlas.
[nodemon] starting `node index.js`
Note-It backend listening at http://localhost:5000
(node:1928) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.createIndex()` buffering timed out after 10000ms
at Timeout.<anonymous> (C:\Users\Meet\OneDrive\Desktop\note-it-backend-api\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:149:23)
at listOnTimeout (internal/timers.js:557:17)
at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1928) 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:1928) [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.
***********************Connected to MongoDB successfully***********************
I cant make any HTTP requests because of this
The db.js contents are :
const mongoose = require('mongoose');
// Connection string for MongoDB ATLAS
const mongoURL = "mongodb+srv://new-meeti:<password>#meet-dev.cc0qw.mongodb.net/?retryWrites=true&w=majority"
const connectToMongo = () => {
// .connect method taks 2 args, 2nd one is a callback function
mongoose.connect(mongoURL, () => {
console.log("***********************Connected to MongoDB successfully***********************");
})
}
module.exports = connectToMongo;
This was more than a year old project hosted on heroku but then I had to shift to to some other hosting service so again deploying is getting problematic due to various deprecation issues I think.
A help would be really appreciated. Thanks :)
PS : I checked my Network access on the MongoDB Atlas and 0.0.0.0/0 (includes your current IP address) is active.

NestJS - UnhandledPromiseRejectionWarning

Short version:
I am looking for a way to way to run my NestJS application with the '--trace-warnings' flags that nodeJS offers. Is there some way to do this or does NestJS offer something similar?
Long version:
Hi! NestJS noob here. I am trying to run a dev version of the NestJS application I am working on. However, on starting the application I get the error below.
Clearly, it is missing a catcherror somewhere! However, the dev version has a LOT of updates and this error can be anywhere so I am hoping for a more efficient way of finding this bug than just checking every single new function! In the errormessage there are a few tips on flags to run while starting the application (node --trace-warnings ...). However, these are for node and not NestJS.
So therefore my question; is there some way to run NestJS with the --trace-warnings flag or some other efficient way to find where I am missing the catcherror?
Thanks in advance!
Error:
(node:72899) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:72899) 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:72899) [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.
(node:72899) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
(node:72899) 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: 2)
Well, 6379 is the Redis default port, it seems like Nest cannot connect to it :)
By the way, give a look at this paragraph:
https://docs.nestjs.com/exception-filters#catch-everything
In order to catch every unhandled exception (regardless of the
exception type), leave the #Catch() decorator's parameter list empty,
e.g., #Catch().
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '#nestjs/common';
#Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
To answer your specific question:
I am looking for a way to way to run my NestJS application with the '--trace-warnings' flags that nodeJS offers. Is there some way to do this or does NestJS offer something similar?
I've been trying to do the same thing, and there seems to be next-to-no documentation online on how to do this. Through some trial and error, I've found that this seems to work:
node --trace-warnings -r source-map-support/register --inspect dist/main
Note that this won't rebuild your application (neither when you first start it up, or by watching for changes), so you'll need to do that manually. The debugger is enabled via --inspect switch, remove that if you don't need to debug.
try to use a npm response / request logger like winston or moesif you will get a lot of help trust me.
here are the links for these library for nestjs
https://github.com/scalio/nest-couchdb

AXIOS_INSTANCE_TOKEN error in Nestjs startup

My nestjs app starts to blow up pointing to AXIOS_INSTANCE_TOKEN error and request for the module containing AXIOS_INSTANCE_TOKEN to be imported... the thing is the only module using Axios is HttpModule and it was imported from the start. this is what I have:
the error:
] [Nest] 94322 - 02/04/2021, 12:16:31 PM [Genysis Gateway] Start Gateway
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [NestFactory] Starting Nest application...
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [InstanceLoader] RavenModule dependencies initialized
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [InstanceLoader] MsConnectorModule dependencies initialized
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [InstanceLoader] ChatModule dependencies initialized
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [InstanceLoader] HttpModule dependencies initialized
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [InstanceLoader] HttpModule dependencies initialized
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [InstanceLoader] HttpModule dependencies initialized
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [InstanceLoader] ConfigHostModule dependencies initialized
[0] [Nest] 94322 - 02/04/2021, 12:16:32 PM [ExceptionHandler] Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument AXIOS_INSTANCE_TOKEN at index [0] is available in the AppModule context.
[0]
[0] Potential solutions:
[0] - If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current AppModule?
[0] - If AXIOS_INSTANCE_TOKEN is exported from a separate #Module, is that module imported within AppModule?
[0] #Module({
[0] imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]
[0] })
THIS IS THE APP MODULE:
......
#Module({
imports: [
RavenModule,
ConfigModule.forRoot({
isGlobal: true,
load: [configuration],
}),
HttpModule.register({
timeout: 5000,
maxRedirects: 5,
}),
AuthModule,
UserModule,
.......
I noticed that the three references to HttpModule initialized ok. Also, I have a check and the two other modules with HttpModules have correctly imported HttpModule in the Module and the injected the HttpService in the Service.
I also noticed that the build died while building ConfigModule...not sure what that means?.... I have also deleted node_modules and run npm I twice and upgrade my nestjs/common from 7.5.1 to 7.6.11 all to no avail.
I would really appreciate any insights on this! Thanks in advance.
Apparently I somehow included HttpService in the app module as a provider and exported it also. Removing both entries resolved the problem.
I had this issue. your appModule is Ok all you need to do is to remove the HttpService from the provider and import HttpModule in order to have HttpService provider available to use.
also see https://docs.nestjs.com/techniques/http-module#getting-started

NestJs installation on iisnode and Unhandled promise rejection

When I try to install NestJs application on IIS-server (with iisnode installed) I always just encounter issue which says
"...Error: listen EADDRINUSE: address already in use :::3450.." (see below)
And, as you can see from the console.log (see below), the NestJs application is first fully initialized and launched, but then comes always the port already in use issue. And it persists no matter how many different ports I try. I have also tried to restart iisnode.exe and killed the process and the port but it does not help. Anyone any experience with this and found the solution?
node dist/main
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[NestFactory] [39m[32mStarting Nest application...[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[InstanceLoader] [39m[32mConfigHostModule dependencies initialized[39m[33m +34ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[InstanceLoader] [39m[32mAppModule dependencies initialized[39m[33m +0ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[InstanceLoader] [39m[32mConfigModule dependencies initialized[39m[33m +1ms[39m
hello from NestJs app
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[RoutesResolver] [39m[32mAppController {}:[39m[33m +13ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[RouterExplorer] [39m[32mMapped {, GET} route[39m[33m +4ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[RoutesResolver] [39m[32mItemsController {/items}:[39m[33m +0ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[RouterExplorer] [39m[32mMapped {/items, GET} route[39m[33m +1ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[RouterExplorer] [39m[32mMapped {/items/:id, GET} route[39m[33m +2ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[RouterExplorer] [39m[32mMapped {/items, POST} route[39m[33m +1ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[RoutesResolver] [39m[32mShoppingCartController {/shopping-cart}:[39m[33m +1ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[RouterExplorer] [39m[32mMapped {/shopping-cart, POST} route[39m[33m +0ms[39m
[32m[Nest] 36096 - [39m09/01/2020, 1:43:54 PM [33m[NestApplication] [39m[32mNest application successfully started[39m[33m +4ms[39m
App is running in port: 61302
events.js:292
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::61302
at Server.setupListenHandle [as _listen2] (net.js:1313:16)
at listenInCluster (net.js:1361:12)
at Server.listen (net.js:1447:7)
at ExpressAdapter.listen (C:\...\node_modules\#nestjs\platform-express\adapters\express-adapter.js:45:32)
at NestApplication.listen (C:\...\node_modules\#nestjs\core\nest-application.js:146:26)
at async bootstrap (C:\...\dist\main.js:8:9)
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1340:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 61302
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! nest-restaurant-api#0.0.1 start:prod: `node dist/main`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the nest-restaurant-api#0.0.1 start:prod 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:\...\AppData\Roaming\npm-cache\_logs\2020-09-01T12_43_54_285Z-debug.log
In iisnode server error log I can also find the following:
(this proved to be logged in previous day - and not to be seen anymore in the logs. So, this iisnode log message may not be relevant for the issue at all)
(node:45472) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(node:45472) UnhandledPromiseRejectionWarning: RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536. Received NaN.
at validatePort (internal/validators.js:182:11)
at Server.listen (net.js:1439:5)
at ExpressAdapter.listen (C:\...\node_modules\#nestjs\platform-express\adapters\express-adapter.js:45:32)
at NestApplication.listen (C:\...\node_modules\#nestjs\core\nest-application.js:146:26)
at async bootstrap (C:\...\dist\main.js:7:5)
(node:45472) 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:45472) [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.
In addition here is the /dist/main.js file in its present form (I have added those try / catch -statements).
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("#nestjs/core");
const app_module_1 = require("./app.module");
async function bootstrap() {
try {
const app = await core_1.NestFactory.create(app_module_1.AppModule);
await app.listen(parseInt(process.env.PORT) || 8080)
.catch((e) => {
console.error(e);
process.exit(1);
});
console.log('App is running in port: ' + process.env.PORT);
}
catch (error) {
console.log("Error message: " + error);
}
}
bootstrap().catch(e => {
console.error(e);
});
//# sourceMappingURL=main.js.map
As suggested by Bruce Zhang in his comment I will post the solution I found by myself.
So, the cause of the error was quite silly indeed.
1.) Using Plesk controlling panel (in IIS-server), irrespective of whether the NestJs application is deployed to site root or sub folder (like the default dist folder ), it is essential to get path settings to project to refer correctly:
Now, in the image above, path settings to project are correct when deployed to sub folder (i.e. default build folder dist). My error was that path reference for the Application Startup File was "/dist/main.js" as it should be just main.js.
After this simple correction app started normally with default IIS-port (port 80 and for SSL-protected connection 443). The main.ts -file does not have to anything else than just the following with the IIS default port fetched automatically via process.env.PORT:
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT);
}
bootstrap();
2.) The second simple thing that must be correctly configured is web.config (and this was originally correct in my case):
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="dist/main.js" verb="*" modules="iisnode" />
</handlers>
<iisnode nodeProcessCommandLine="C:\Program Files\nodejs\node.exe">
</iisnode>
<rewrite>
<rules>
<rule name="nestjs">
<match url="/*" />
<action type="Rewrite" url="main.js" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
I hope this help those who might get confused with IISnode settings in Plesk. And these settings apply generally to all Node.js applications, they are not limited to NestJs which is just upper level framework on node.js, and particularly much on Express. But error messages in IISNode can sometimes be a bit misleading and it takes some pain to see through them.
NestJs is really awesome and it is great that those who have to, or love to, use IIS can easily deploy super modern NestJs backend apps to IIS-server, thanks to those who implemented IISnode.

How to see stacktrace / cause of an error in Jest?

I'm trying to debug a nodeJS app.
I have some code which causes an error, a variable is undefined.
When I run the code normally, the error is very clear and easy to find:
without jest:
➜ server git:(dc/build) ✗ node test/runner.js
/Users/dc/dev/exiteer/xbot/server/src/mup/Story.js:24
Logger.logObj('loaded story', {name: doc.name})
^
ReferenceError: doc is not defined
at Story.reload (/Users/dc/dev/exiteer/xbot/server/src/mup/Story.js:24:42)
at Game.reload (/Users/dc/dev/exiteer/xbot/server/src/mup/Game.js:48:16)
at Object.<anonymous> (/Users/dc/dev/exiteer/xbot/server/test/runner.js:4:10)
Sweet, I can fix it.
Now, Jest has some nice tooling for writing tests so I thought I'd try that.
But the errors are seemingly impossible to track down:
➜ server git:(dc/build) ✗ npm run jest
> cbg#0.1.0 jest /Users/dc/dev/exiteer/xbot/server
> jest
PASS src/index.test.js
(node:23114) UnhandledPromiseRejectionWarning: ReferenceError: doc is not defined
(Use `node --trace-warnings ...` to show where the warning was created)
(node:23114) 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:23114) [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.
FAIL src/mup/Actor.test.js
● Console
console.log
actors undefined
at Object.<anonymous> (src/mup/Actor.test.js:9:13)
● Game.js › can load a story
expect(received).toHaveLength(expected)
Matcher error: received value must have a length property whose value must be a number
Received has value: undefined
8 |
9 | console.log('actors', game.story.room.name.actors)
> 10 | expect(game.story.room.actors).toHaveLength(1);
| ^
11 | const actor = game.story.room.actors[0]
12 | const reply = actor.sayTo('hi')
13 | expect(reply).toBe('hi back from Sid')
at Object.<anonymous> (src/mup/Actor.test.js:10:36)
This tells me where my tests failed, but I'd prefer to know where the actual error is. Tests aren't the end goal here, a working app is.
Googling around I found and tried this but it gives the same error message.
node --trace-warnings node_modules/.bin/jest --no-cache
➜ server git:(dc/build) ✗ npm run test
> cbg#0.1.0 test /Users/dc/dev/exiteer/xbot/server
> node --trace-warnings node_modules/.bin/jest --no-cache
(node:23263) UnhandledPromiseRejectionWarning: ReferenceError: doc is not defined
at emitUnhandledRejectionWarning (internal/process/promises.js:151:15)
at processPromiseRejections (internal/process/promises.js:211:11)
at processTicksAndRejections (internal/process/task_queues.js:98:32)
(node:23263) 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)
which gives a tiny bit more info but an
at emitUnhandledRejectionWarning (internal/process/promises.js:151:15)
at processPromiseRejections (internal/process/promises.js:211:11)
at processTicksAndRejections (internal/process/task_queues.js:98:32)
This is not very helpful for debugging my code.
Also Jest seems to swallow all console.log as if it's doing the best to make debugging as painful as possible. When your environment doesn't even log, its a real WTF moment.
This was a bug in Node.js or Jest depending on your perspective - I fixed this a few months ago.
It happens because Jest throws errors in JavaScript coming from a different realm - so instanceof Error fails. You can see my PR here.
There is a workaround if you are forced to use old versions of Node or Jest here:
process.on('unhandledRejection', (reason) => {
console.log(reason); // log the reason including the stack trace
throw e;
});
We added this hook in Node 1.3 so it should be safe to use in virtually all Node code.

Resources