Cannot find module 'posts.graphql' using loadSchema and GraphQLFileLoader from graphql-tools - node.js

I am trying to load schema from a specific folder.
I am trying to not using Apollo, a pretty good solution that I found is loadSchema from #graphql-tools/load.
const { loadSchema } = require('#graphql-tools/load');
const { GraphQLFileLoader } = require('#graphql-tools/graphql-file-loader');
async function getLoadedSchema() {
const schemas = await loadSchema('/absolute/path/*.graphql', {
loaders: [new GraphQLFileLoader()]
})
console.log('mySchema', schemas);
}
By launching the server, I get this error:
Running a GraphQL API server at http://localhost:4000/graphql
(node:30146) UnhandledPromiseRejectionWarning: Error: Cannot find module 'posts.graphql'
Require stack:
- /absolute/path/src/routes/users/create/noop.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/myUser/.asdf/installs/nodejs/12.22.1/.npm/lib/node_modules/ts-node/node_modules/#cspotcode/source-map-support/source-map-support.js:679:30)
at resolveFileName (/absolute/path/node_modules/resolve-from/index.js:29:39)
at resolveFrom (/absolute/path/node_modules/resolve-from/index.js:43:9)
at module.exports (/absolute/path/node_modules/resolve-from/index.js:46:47)
at resolveFilePath (/absolute/path/node_modules/#graphql-tools/import/index.js:395:20)
at visitFile (/absolute/path/node_modules/#graphql-tools/import/index.js:57:20)
at processImports (/absolute/path/node_modules/#graphql-tools/import/index.js:291:41)
at visitFile (/absolute/path/node_modules/#graphql-tools/import/index.js:66:82)
at Object.processImport (/absolute/path/node_modules/#graphql-tools/import/index.js:36:1
I don't really know where the comes from.
Do you have some ideas ?

Related

Node - Migrate postgres DB programmatically using jest globalsetup.js file

I am trying to use testcontainers(https://github.com/testcontainers/testcontainers-node/tree/master/src/modules/postgresql) to spin up a postgres db and use that to run my jest tests.
I used globalsetup.js file to run the container spinup code. The container is spinning successfully, no problem in that, but the issue arises when i try to migrate the db. For Migrating i use typeorm's connection.runMigrations function. Somehow the migration is not working.
All my files, except globalsetup.js is a typescript file.
My connection string looks like this:
createConnection({
url: `postgres://${username}:${encodeURIComponent(password)}#${host}:${port}/${database}`
entities: process.env.TYPEORM_ENTITIES.split(‘,’),
migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
type: 'postgres,
});
TYPEORM_ENTITIES=src/db/entities/**/.ts
TYPEORM_MIGRATIONS=src/db/migrations/.ts
and in my jest.globalSetup.js:
const {createConnection} = require('typeorm')
module.exports = async () => {
/* Code for Container Startup */
process.env.NODE_ENV = ‘test’;
const connection = await createConnection({
url: `postgres://uno-test:dia#localhost:${process.env.TYPEORM_PORT}/cart-test?sslmode=disable`,
entities: process.env.TYPEORM_ENTITIES.split(‘,’),
migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
type: ‘postgres’,
});
await connection
.runMigrations()
.then((value) => console.log(‘Migration Done’, value))
.catch((e) => console.log(e));
await connection
.close()
};
Error Message is:
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from ‘typeorm’;
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at /Users/webmaster/CART/cart-portal-service/node_modules/typeorm/util/ImportUtils.js:29:52
at step (/Users/webmaster/CART/cart-portal-service/node_modules/tslib/tslib.js:144:27)
I tried changing the entities and migrations constants to
TYPEORM_ENTITIES=src/db/entities/**/.{ts,js}
TYPEORM_MIGRATIONS=src/db/migrations/.{ts,js}
If i do above chagne, I no longer see the error, but my db is empty as in no tables are created.
Versions:
Node - 16.6.0
Typeorm - 0.2.45
typescript: 4.7.4
jest: 28.1.3

Error in VSCode, while i try create a spotify discord bot: [ SyntaxError: Cannot use import statement outside a module ] with node.js [duplicate]

This question already has answers here:
SyntaxError: Cannot use import statement outside a module
(34 answers)
Closed 23 days ago.
I can't execute and debug my discord bot, having an error in debugging console.
This is my code in the bot:
const discord = require('discord.js');
const client = new discord.Client({
ws: { intents: discord.Intents.ALL },
});
import spotify from 'spotify-web-api-js';
const spotifyAPI = new spotify();
import { MessageEmbed } from 'discord.js';
//Spotify Credentials
spotifyAPI.setAccessToken('HIDDEN');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content.startsWith('!play')) {
let songName = message.content.split(" ").slice(1).join(" ");
spotifyAPI.searchTracks(songName)
.then(function(data) {
let song = data.tracks.items[0];
let songName =song.name;
let songUrl =song.preview_url;
let songAuthor =song.artists[0].name;
let songEmbed = new MessageEmbed()
.setTitle(`Playing ${songName}`)
.setURL(songUrl)
.setAuthor(songAuthor)
.setColor('#0099ff')
message.channel.send(songEmbed);
}, function(err) {
console.error(err);
message.channel.send("Sorry, I couldn't find the song you requested. Please try again with a different name or check your internet connection.");
});
}
});
client.login('HIDDEN');
And i have this error in my debugging console:
Uncaught SyntaxError C:\Users\MY_USERNAME\Proyectos de VS Code\spoticord\spoticord.js:6
import spotify from 'spotify-web-api-js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at compileFunction (vm:360:18)
at wrapSafe (internal/modules/cjs/loader:1088:15)
at Module._compile (internal/modules/cjs/loader:1123:27)
at Module._extensions..js (internal/modules/cjs/loader:1213:10)
at Module.load (internal/modules/cjs/loader:1037:32)
at Module._load (internal/modules/cjs/loader:878:12)
at executeUserEntryPoint (internal/modules/run_main:81:12)
at <anonymous> (internal/main/run_main_module:23:47)
Process exited with code 1
I tried update discord.js, spotify-web-api-js, reinstall both modules.
But gives another errors like:
TypeError: Cannot read properties of undefined (reading 'ALL')
SyntaxError: Identifier 'Discord' has already been declared
Valid intents must be provided for the Client.
Your package's settings are for "CommonJS", when import is allowed for "module" types.
// at line 6
import spotify from 'spotify-web-api-js'
// at line 9
// this must be replaced also, like at line 6
import { MessageEmbed } from 'discord.js';
There are two correct solutions.
Set "type" as "module" in "package.json" and use import <name> from <module> instead of const <name> = require("<module>")
Replace import spotify from 'spotify-web-api-js'; with const spotify = require("spotify-web-api-js"), because "CommonJS" doesn't support "import"

Error in constructing Graphql schema and resolvers in deployment of Next.js app on Vercel

I am using graphql-tools to merge Types and Schemas. My graphql server runs on the end point api/graphql
import { mergeTypeDefs, mergeResolvers } from "#graphql-tools/merge";
import { loadFilesSync } from "#graphql-tools/load-files";
import path from "path";
const typesArray = loadFilesSync(path.join(process.cwd(), "./**/*.graphql"));
export const types = mergeTypeDefs(typesArray);
const resolversArray = loadFilesSync(
path.join(process.cwd(), "./**/*.resolvers.*")
);
export const resolvers = mergeResolvers(resolversArray);
The graphql endpoint works locally, however upon deployment to Vercel, I get the following error with Serverless Function when an API call is made to api/graphql
ERROR Unhandled error during request: Error: Query root type must be provided.
at assertValidSchema (/var/task/node_modules/graphql/type/validate.js:69:11)
at assertValidExecutionArguments (/var/task/node_modules/graphql/execution/execute.js:150:35)
at executeImpl (/var/task/node_modules/graphql/execution/execute.js:98:3)
at Object.execute (/var/task/node_modules/graphql/execution/execute.js:60:63)
at Object.generateSchemaHash (/var/task/node_modules/apollo-server-core/dist/utils/schemaHash.js:15:32)
at ApolloServer.generateSchemaDerivedData (/var/task/node_modules/apollo-server-core/dist/ApolloServer.js:269:41)
at new ApolloServerBase (/var/task/node_modules/apollo-server-core/dist/ApolloServer.js:161:38)
at new ApolloServer (/var/task/node_modules/apollo-server-micro/dist/ApolloServer.js:18:1)
at Module.dCYn (/var/task/.next/serverless/pages/api/graphql.js:490:22)
at __webpack_require__ (/var/task/.next/serverless/pages/api/graphql.js:23:31)
at Module.GfcW (/var/task/.next/serverless/pages/api/graphql.js:251:23)
at __webpack_require__ (/var/task/.next/serverless/pages/api/graphql.js:23:31)
at /var/task/.next/serverless/pages/api/graphql.js:91:18
at Object.<anonymous> (/var/task/.next/serverless/pages/api/graphql.js:94:10)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
I believe it has to do with a mess up in the path for loadFilesSync. I tried replacing process.cwd() with __dirname, but it didn't work. I pretty much have scoured through every single resource on the internet but no luck. Any help would be greatly appreciated.

How to remove TypeError: "x" is not a function?

I am trying to learn how to make a discord bot and pull data from this API called Ergast (http://ergast.com/mrd). I found this npm (https://github.com/estevE11/f1-stats) which uses NodeJS implementation to get a historical record of F1 data from Ergast API. Sorry for the bad wording I am still trying to learn the lingo.
I followed what was stated in the npm documentation for installing it and tried using the example to get data from the API. However when I run the code in index.js I get the error "TypeError: "x" is not a function". When I go into the node_modules "f1-stats" folder and run the code from main.js I do get the correct result.
index.js:
const client = new Discord.Client(); //This will be our client
const { prefix, token } = require('./config.json');//const PREFIX = '!';
const f1s = require('f1-stats');
//module.exports.f1s = f1s; //Still causes the TypeError
f1s("2008 drivers", (res) => {
console.log(res);
});
The error message I get in index.js:
f1s("2008 drivers", (res) => {
^
TypeError: f1s is not a function
at Object.<anonymous> (C:\Users\RyanPC\Documents\DiscordBot\index.js:8:1)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
node_modules/f1-stats/main.js:
const f1s = require("./f1-stats"); // "./" is used because module is located in the same folder as the Node.js file
f1s("2008 drivers", (res) => {
console.log(res);
});
when I run it in node_modules/f1-stats/main.js:
{ MRData:
{ xmlns: 'http://ergast.com/mrd/1.4',
series: 'f1',
url: 'http://ergast.com/api/f1/2008/drivers.json',
limit: '30',
offset: '0',
total: '22',
DriverTable: { season: '2008', Drivers: [Array] } } }
Because f1-stats doesn't export anything so when you import it. It is empty. The correct file you need to import is f1-stats/f1-stats.
const f1s = require('f1-stats/f1-stats');
try importing f1s properly , you are getting error because you have not imported the function properly , in other words...check what is being exported from what are you trying to import....hope it solves the problem.

Type Error: Cannot read property 'hasListCollectionsCommand' of null

I'm trying to get all collection names in mongodb (v4.0.2) and using mongodb#3.1.10 nodejs driver. From the docs, I can see that listCollections might work, but running the following:
const Db = require('mongodb').Db
const Server = require('mongodb').Server
const db = new Db(dbName, new Server(host, port, options), {})
db.listCollections().toArray((error, collectionNames) => {
console.error(error)
console.log(JSON.stringify(collectionNames))
})
… leads to this error:
if (this.serverConfig.capabilities().hasListCollectionsCommand) {
TypeError: Cannot read property 'hasListCollectionsCommand' of null
at Db.listCollections ({path}/node_modules/mongodb/lib/db.js:493:39)
at db.createCollection ({path}/sampleMongoDB.js:19:8)
at err ({path}/node_modules/mongodb/lib/utils.js:415:14)
at executeCallback ({path}/node_modules/mongodb/lib/utils.js:404:25)
at executeOperation ({path}/node_modules/mongodb/lib/utils.js:422:7)
at Db. ({path}/node_modules/mongodb/lib/db.js:431:12)
at Db.deprecated [as createCollection] ({path}/node_modules/mongodb /lib/utils.js:661:17)
at Object.< anonymous > ({path}/sampleMongoDB.js:18:6)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
My questions are:
Is there a docs site for MongoDB NodeJs drivers where we can refer examples from?
If not, what's the correct way to query?
I was able to work it out. The MongoClient's instance returns a db instance, which inturn helps run mongodb.Db methods.
Here's a sample code that worked (Ref. to MongoDB guides)
const options = {
useNewUrlParser: true, // Add this, if you wish to avoid {https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars} issue
}
const client = new MongoClient(connectionUri, options)
return client.connect().then(() => {
const db = client.db(dbName)
return db.listCollections()
.toArray()
.then((collections) => {
// Collections array
})
})
#Community mods - if required, kindly close this question.

Resources