I am getting a required error using graphql tools - javascript

I am building a gql server application using apollo server.
When I try to load my .graphql files using import { loadFilesSync } from '#graphql-tools/load-files', this works very well, but when I load my resolver files, i get an error
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /userpath/index.js from /userpath/server-gql/noop.js not supported.
Instead change the require of index.js in /userpath/server-gql/noop.js to a dynamic import() which is available in all CommonJS modules.
at Object.newLoader [as .js] (/userpath/server-gql/node_modules/pirates/lib/index.js:141:7)
at file:///userpath/server-gql/node_modules/#graphql-tools/load-files/esm/index.js:104:33
at Array.map (<anonymous>)
at loadFilesSync (file:///userpath/server-gql/node_modules/#graphql-tools/load-files/esm/index.js:95:10)
at file:///userpath/server-gql/schema.js:20:24
at async Promise.all (index 0) {
code: 'ERR_REQUIRE_ESM'
}
I am using "type": "module" in my package.json.
Here's my code snippet for where i get the error
import path from 'path'
import { fileURLToPath } from 'url'
import { loadFilesSync } from '#graphql-tools/load-files'
import { mergeTypeDefs, mergeResolvers } from '#graphql-tools/merge'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const typesArray = loadFilesSync(path.join(__dirname, '.'), {
recursive: true,
extensions: ['graphql'],
})
const resolversArray = loadFilesSync(path.join(__dirname, './graphql/**/*.resolvers.js'), {
recursive: true,
extensions: ['js'],
})
const newResolversArray = resolversArray.slice(1)
export const typeDefs = mergeTypeDefs(typesArray)
export const resolvers = mergeResolvers(newResolversArray)
I think the error occurs in the resolvers array.

I was running into a very similar issue and found this workaround/solution worked for me: https://github.com/ardatan/graphql-tools/issues/1750#issuecomment-655828240
I had to modify that answer a bit to get it working in my codebase...below is what my own resolverFiles snippet now looks like (I'm not 100% sure what your import/naming conventions look like, or I'd try to apply this to your code snippet).
I have a mixed, nested directory schema/ that contains resolver files of the format SomethingResolvers.ts. Each of these look like the following (I'm using codegen):
import { Resolvers } from "../../generated/graphql";
export const resolvers: Resolvers = { /* resolver implementations */ };
const resolverFiles = await loadFiles(
path.join(__dirname, "**/*Resolvers.js"),
{
requireMethod: async (path) => {
const module = await import(pathToFileURL(path).toString());
return module["resolvers"];
},
recursive: true,
}
);

Related

Why are imported modules on serverless functions undefined?

TL;DR - why do imports return undefined? Especially for native Node modules like path?
I have a very small test application, built with Vite, that has a single endpoint in the /api directory. I created this just to play around with Vite + Vercel.
I have only 2 module imports for my endpoint - path and fs-extra. Both are returning as undefined. I was getting cannot read join of undefined errors with the path module, so I wrapped everything in a try/catch just to see if the endpoint responds. It does. See my code below.
import type {VercelRequest, VercelResponse} from '#vercel/node'
import path from 'node:path' // I've also tried 'path'
import fs from 'fs-extra'
export default function handler(req: VercelRequest, res: VercelResponse) {
// Both of these log 'undefined' on my Vercel dashboard for function logs.
console.log('path module:', path)
console.log('fs module:', fs)
try {
// https://vercel.com/guides/how-can-i-use-files-in-serverless-functions
const pathFromProjectRootToFile = '/api/usersData.json'
const usersDataFilePath = path.join( // THIS IS WHERE THE ERROR HAPPENS 🙃
process.cwd(),
pathFromProjectRootToFile
)
const usersData = fs.readJSONSync(usersDataFilePath)
res.json({users: usersData})
} catch (e) {
res.json({error: errorToObject(e as Error)})
}
}
function errorToObject(err?: Error): Record<string, string> | null {
if (!err || !(err instanceof Error)) return null
const obj: Record<string, string> = {}
Object.getOwnPropertyNames(err).forEach(prop => {
const value = err[prop as keyof Error]
if (typeof value !== 'string') return
obj[prop] = value
})
return obj
}
As an aside, instead of node:path I also tried just path, but same thing - undefined. And I do have fs-extra as a dependency in my package.json.
When deploying a Vite app on Vercel and utilizing the /api directory for a back end with Serverless Functions, Node modules need to be imported via require, not import. The import syntax works for types and local modules. See this answer (and conversation) in Vercel's community discussions.
import type {VercelRequest, VercelResponse} from '#vercel/node'
import localModule from '../myLocalModule'
const path = require('path')
const fsOriginal = require('fs')
const fs = require('fs-extra')
// Rest of the file here...

Module "util" has been externalized for browser compatibility. Cannot access "util.promisify" in client code

I am trying to scrap linkeidn profile using this library:
https://www.npmjs.com/package/#n-h-n/linkedin-profile-scraper.
this is my code:
<script>
import { LinkedInProfileScraper } from '#matidiaz/linkedin-profile-scraper';
import { onMount } from 'svelte';
import { session } from '$app/stores';
onMount(async () => {
const token = session?.provider_token;
console.log(token);
const scraper = new LinkedInProfileScraper({
sessionCookieValue: token,
keepAlive: false
});
// Prepare the scraper
// Loading it in memory
await scraper.setup();
const result = await scraper.run('https://www.linkedin.com/in/jvandenaardweg/');
console.log(result);
});
</script>
I am using sveltekit to get the information, can someone point out how to solve this prb,I am not finding much information online.
Hi what worked for me was to fix the vite.config.ts into something like this:
resolve: {
alias: {
process: "process/browser",
stream: "stream-browserify",
zlib: "browserify-zlib",
util: "util/",
'#': path.resolve(__dirname, './src'),
}
}
where we actually resolve the alias of util and add to it 'util/'
npm i util,
however this lib continues giving errors so I removed it.

How to setup clipboardy in cypress 10?

I'm pretty new to cypress. I tried to install clipboardy to one of my project.
But the guide that I found online like this mostly setup on the older cypress which is using the plugins/index.js file.
I tried something like this and got error
const { defineConfig } = require("cypress");
const createBundler = require("#bahmutov/cypress-esbuild-preprocessor");
const addCucumberPreprocessorPlugin =
require("#badeball/cypress-cucumber-preprocessor").addCucumberPreprocessorPlugin;
const createEsbuildPlugin =
require("#badeball/cypress-cucumber-preprocessor/esbuild").createEsbuildPlugin;
const clipboardy = require("clipboardy");
module.exports = defineConfig({
e2e: {
async setupNodeEvents(on, config) {
const bundler = createBundler({
plugins: [createEsbuildPlugin(config)],
});
on("file:preprocessor", bundler);
await addCucumberPreprocessorPlugin(on, config);
on('task', {
getClipboard () {
return clipboardy.readSync();
}
});
return config;
},
specPattern: "cypress/e2e/features/*.feature",
baseUrl: "XXXXXXXXXXXXX",
chromeWebSecurity: false,
},
});
The error
Error screen
Stack Trace
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\node_modules\clipboardy\index.js from C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js not supported.
Instead change the require of index.js in C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js to a dynamic import() which is available in all CommonJS modules.
at Object. (C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js:8:20)
at async Promise.all (index 0)
at async loadFile (C:\Users\XXXX\AppData\Local\Cypress\Cache\10.4.0\Cypress\resources\app\node_modules\#packages\server\lib\plugins\child\run_require_async_child.js:106:14)
at async EventEmitter. (C:\Users\XXXX\AppData\Local\Cypress\Cache\10.4.0\Cypress\resources\app\node_modules\#packages\server\lib\plugins\child\run_require_async_child.js:116:32)
It's because the clipboardy package has type: "module" in it's 'package.json'.
This tells anything that uses the package that you should use import not require to load the package.
Use dynamic imports, as hinted in the error message
Instead change the require of index.js in ... to a dynamic import()
const clipboard = import('clipboardy')

SyntaxError: Unexpected reserved word "await"

I keep getting this error even thought I am in a asynchronous function...
import { dirname, join } from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export async function importer(client) {
const dir = join(__dirname, "../../commands/")
const commandCategories = readdirSync(dir)
for (let cat of commandCategories) {
const commandFiles = readdirSync(join(dir, cat)).filter(files => files.endsWith(".js"));
for (const file of commandFiles) {
const command = await import(join(dir, cat, file));
client.commands.set(command.default.name, command.default);
}
}
}
Is there something I am missing? I definitely need the await part in import in const command. It imports a few commands then it drops the mentioned error in title on the console output.
Thanks.
The problem isn't the importer code, it's in one of the modules you attempted to import (and import crashes on parsing it)!
It's a bug in node that such a non-helpful error is thrown when this syntax error is encountered during dynamic import.
Try logging the filenames before importing them so you can see at which file it crashes. Once you know which file failed to parse, do a static import of it for testing, so you can get a proper error that tells you which line has the issue.

Module Import error - cannot find module

I was trying to import the module dynamically in ES6 on Meteor application. But getting an error cannot find module. The same import works when I'm using the static import statement.
Please have a look at the below code -
const JOBS = ['update-report-cron'];
const jobs = {
start() {
JOBS.forEach((job) => {
console.log(`job ${job} has been started`);
let fileName = './' + job + '.js';
console.log(require(fileName));
})
}
};
module.exports = {jobs};
ERROR - Cannot find module './update-report-cron.js'
Try
export default const jobs = {
// your code
}
When you import, use
import { jobs } from './update-report-cron.js'
Ru's answer is not correct, not sure how it's your answer.
Try
export default const jobs = {
// your code
}
When you import, use
import jobs from './update-report-cron.js'

Categories

Resources