GraphQL Tutorial - Expected undefined to be a GraphQL schema - node.js

I try to learn GraphQL. I created a project and I did what this page says.
Install
npm init
npm install graphql --save
Server.js
var { graphql, buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
};
// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
console.log(response);
});
Run
node server.js
This returns me an error.
throw new Error(
^
Error: Expected undefined to be a GraphQL schema.
at assertSchema (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\type\schema.js:35:11)
at validateSchema (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\type\validate.js:34:28)
at graphqlImpl (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:52:64)
at C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:21:43
at new Promise (<anonymous>)
at graphql (C:\Users\BK\Projects\Test\graphql-test\node_modules\graphql\graphql.js:21:10)
at Object.<anonymous> (C:\Users\BK\Projects\Test\graphql-test\server.js:18:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
Versions
graphql: "^16.0.1"
node : v16.13.0

I was following the same tutorial and I had the same problem. After going to the next page, as U Rogel suggested, I had the following problem:
Could not resolve dependency:
npm ERR! peer graphql#"^14.7.0 || ^15.3.0" from express-graphql#0.12.0
npm ERR! node_modules/express-graphql
So, I decided to modify my graphql version in the package.json:
"dependencies": {
"express": "^4.17.1",
"express-graphql": "^0.12.0",
"graphql": "^14.7.0"
}
Then I ran npm install, went back to the first page and it worked!
I think the problem is that version 16+ does not work with the basic examples.

Related

Vercel Serverless function results in "Cannot find module 'content-type'" when accessing req.body

I'm using NextJS with Vercel Serverless as described in this answer - https://stackoverflow.com/a/63659707/2826679 . My NodeJS function fails with an error message when I'm running it locally using vercel dev or when it's deployed to vercel servers.
My <PROJECT_ROOT>/api/report.ts looks like this and it fails at printing "3 req.body".
import type { VercelRequest, VercelResponse } from '#vercel/node';
export default async function handler(req: VercelRequest, res: VercelResponse) {
if (req.method === 'POST') {
console.log("1")
console.log("2", req)
console.log("3", req.body)
const data = {
test: "test"
};
return res.status(200).setHeader('content-type', 'application/json').end(JSON.stringify(data));
} else {
return res.status(404);
}
}
Error:
Unhandled rejection: Error: Cannot find module 'content-type'
Require stack:
- /Users/piotr/.config/yarn/global/node_modules/#vercel/node-bridge/helpers.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/piotr/.config/yarn/global/node_modules/#cspotcode/source-map-support/source-map-support.js:811:30)
at Function.Module._load (node:internal/modules/cjs/loader:885:27)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.909 (/Users/piotr/.config/yarn/global/node_modules/#vercel/node-bridge/helpers.js:262:33)
at __webpack_require__ (/Users/piotr/.config/yarn/global/node_modules/#vercel/node-bridge/helpers.js:328:42)
at parseBody (/Users/piotr/.config/yarn/global/node_modules/#vercel/node-bridge/helpers.js:19:45)
at IncomingMessage.get [as body] (/Users/piotr/.config/yarn/global/node_modules/#vercel/node-bridge/helpers.js:212:27)
at handler (/Users/piotr/astrology/astroperspective/api/report.ts:7:26) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/piotr/.config/yarn/global/node_modules/#vercel/node-bridge/helpers.js'
]
}
EDIT:
Now, I'm thinking that it has to do something with dependencies in package.json since my package.json is specifically for NextJS
Were you by any chance able to find out what was causing this? I'm running into the same error as well.

Mocha: You need to instantiate using the "new" keyword

I am just exploring mocha and I am facing a strange error. I have a not project and want to write some tests.
I have installed the node
npm install --save-dev mocha
My code is:
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = Web3(ganache.provider());
class Car{
park(){
return 'stopped!';
}
drive(){
return 'vroom';
}
}
describe('Car', () => {
it('Can be', () => {
const car = new Car();
assert.equal(car.park(), 'stopped!');
})
})
I have also updated the Script element in the package.json
"scripts": {
"test": "mocha"
},
When I run the test using the command:
npm run test
I am getting the following Error:
Error: You need to instantiate using the "new" keyword.
Stack Trace:
> blockchain#1.0.0 test
> mocha
Error: You need to instantiate using the "new" keyword.
at Object.packageInit (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/web3-core/lib/index.js:27:15)
at Web3 (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/web3/lib/index.js:39:10)
at Object.<anonymous> (/Users/username/Blockchain/BlockchainEtherium/blockchain/test/inbox.test.js:5:14)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1166:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Function.Module._load (node:internal/modules/cjs/loader:834:12)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0)
at ESMLoader.import (node:internal/modules/esm/loader:409:24)
at importModuleDynamicallyWrapper (node:internal/vm/module:438:15)
at formattedImport (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
at Object.exports.requireOrImport (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:38:28)
at Object.exports.loadFilesAsync (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:91:20)
at singleRun (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/cli/run-helpers.js:125:3)
at Object.exports.handler (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/cli/run.js:370:5)
Looking forward to your help.
Thanks
Just instantiate Web3 with the new keyword as the error message suggests.
Change
const web3 = Web3(ganache.provider());
To
const web3 = new Web3(ganache.provider());

How do I Fix a Cannot find module '.functions/handleCommands.js' error?

Upon running my Bot to have it sign-on after installing a command and event handler I got the error
Error: Cannot find module '.functions/handleCommands.js'
Require stack:
C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js:14:9
at Object.<anonymous> (C:\Users\levan\Desktop\Discordbot\Bot Templates\2 command handling\src\bot.js:19:3)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) { code:
'MODULE_NOT_FOUND',
requireStack: [
'C:\\Users\\levan\\Desktop\\Discordbot\\Bot Templates\\2 command handling\\src\\bot.js'
After looking thru the folder functions and the handleCommands.js, I Still cannot figure out what I'm missing or what I might on messed up. I thought that maybe my module.exports was in the wrong place but moving things around did not solve the issue either.
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const clientId = 'redacted'; // your bots token
const guildId = 'redacted'; // the server id the bot will be on
module.exports = (clinet) => {
clinet.handleCommands = async (commandFolders, path) =>{
clinet.commandArray = [];
for(folder of commandFolders){
const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
clinet.commandArray.push(command.data.toJSON());
}
}
};
};
const rest = new REST({ version: '9' }).setToken(process.env.token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: clinet.commandArray },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
As the error was MODULE_NOT_FOUND I figured that maybe I didn't run all the installs I need to make my bot work. After running thru my npm lists the error persisted.
NPM's Installed
"npm init"
"npm install discord.js"
"npm install dotenv"
"npm install discord.js dotenv"
"npm install #discordjs/rest discord-api-types #discordjs/builders"
My goal is to be the Bot back online and to figure out how to troubleshoot this sort of error in case it comes up again. Any help you can give will be greatly appreciated.
'.functions/handleCommands.js' should have been './functions/handleCommands.js' Caffeine is not a substitute for sleep

Connect Node.js BOT to MS Azure SQL database

I have a working MS Teams bot written in Node.js. The bot asks a series of questions and currently displays the responses at the end by accessing the session variables. All well and good.
Now I am attempting to store the session variables in a MS Azure SQL DB. The DB is correctly set up in Azure as I can access and write data to it in SSMS. But I believe I am probably connecting incorrectly to the DB in my bot code. The bot code I am using is pulled from:
connecting to SQL using Node.js
That code makes sense to me. But how do I use that code in my bot? Here is what I have attempted thus far...
Currently I am using the local memory MemoryBotStorage() and setting to that.
var inMemoryStorage = new builder.MemoryBotStorage();
.set('storage', inMemoryStorage)
In another Microsoft article dealing with the Azure Cosmos DB it states "4.Specify that you want to use your custom database instead of the in-memory storage." So from this I deduce that I hafta add my instantiated sql db to the .set('storage', DB Goes Here) but my attempts have failed and I am not sure if I am even correct?
So my question is how do I correctly access the Azure sql server DB form my bot code - and is the link I provided even the correct way?
Thank you
Note - This code sample worked for me - I was able to connect and query my Azure DB - but it is only DB code and does not take into consideration bot code.
EDIT - Code:
const builder = require('botbuilder');
const builderTeams = require('botbuilder-teams');
const restify = require('restify');
const connector = new builderTeams.TeamsChatConnector(
{
appId: "My app ID,
appPassword: "My App PW",
}
);
var inMemoryStorage = new builder.MemoryBotStorage();
const bot = new builder.UniversalBot(connector, [
function (session) {
session.send("Welcome.");
builder.Prompts.text(session, "Question1?");
},
function (session, results) {
session.dialogData.question1 = results.response;
builder.Prompts.text(session, "Question2?");
},
function (session, results) {
session.dialogData.Question2 = results.response;
builder.Prompts.text(session, "Question3?");
},
function (session, results) {
session.dialogData.Question3 = results.response;
// Begin DB
var Connection = require('tedious').Connection;
var config = {
userName: 'myusername',
password: 'mypw',
server: 'myserver.database.windows.net',
// If you are on Azure SQL Database, you need these next options.
options: { encrypt: true, database: 'mydb' }
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement1();
});
var Request = require('tedious').Request
var TYPES = require('tedious').TYPES;
function executeStatement1() {
request = new Request("INSERT my (Username, Question1, Question2, Question3, StatusDate) VALUES (#Username, #Question1, #Question2, #Question3, CURRENT_TIMESTAMP);", function (err) {
if (err) {
console.log(err);
}
});
request.addParameter('Username', TYPES.NVarChar, session.userData.userName);
request.addParameter('Question1', TYPES.NVarChar, session.dialogData.Question1);
request.addParameter('Question2', TYPES.NVarChar, session.dialogData.Question2);
request.addParameter('Question3', TYPES.NVarChar, session.dialogData.Question3);
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log("ID of inserted item is " + column.value);
}
});
});
connection.execSql(request);
// End DB
// Process request and display details
session.endDialog();
}
]).set('storage', inMemoryStorage)
const server = restify.createServer();
server.post('api/messages', connector.listen());
server.listen(portnumber)
Error when running with npm start:
npm start
> simplebot#1.0.0 start C:\Developer\dailyStatus
> node index.js
C:\Developer\dailyStatus\index.js:81
]).set('storage', inMemoryStorage)
^
SyntaxError: Unexpected token ]
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! simplebot#1.0.0 start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the simplebot#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely...
npm ERR! A complete log of this run can be found in:
npm ERR! C: etc.
FINAL
I was able to able to get this working with this tutorial. Thanks also to Marc LeFleur.
You have several typos. For example, you're missing the closing " on appId:
const connector = new builderTeams.TeamsChatConnector(
{
appId: "My app ID",
appPassword: "My App PW",
}
);
You also can't declare the function executeStatement1() {...} function within the your IDialogWaterfallStep function. This needs to live outside the constructor and called from the IDialogWaterfallStep.

Mongorito: save(...).then is not a function

I tried something similar to the example given on the readme.md file:
var Mongorito = require('mongorito');
var Model = Mongorito.Model;
Mongorito.connect('mongodb://localhost:27017/cr-test');
class User extends Model {
collection() {
return 'users';
}
}
var user1 = new User({
name: "James Gosling",
email: "user1#gmail.com",
password: "changeme"
});
user1.save().then(() => {
console.log('User Created');
});
when I run node --harmony server.js I get this error:
user1.save().then(() => {
^
TypeError: user1.save(...).then is not a function
at Object.<anonymous> (...\app\server.js:24:14)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:980:3
Could someone explain me how could I fix that?
The readme on GitHub is outdated, the project's website now states:
MongoDB ODM for Node.js based on ES6 generators.
No callbacks or promises.
It uses generators, which can find an example of on the getting started page:
'use strict';
function* saveUser () {
var user1 = new User({
name: "James Gosling",
email: "user1#gmail.com",
password: "changeme"
});
yield user1.save();
}
In order for generators to work, you must use 'use strict;' and the function* syntax. This GitHub project has additional examples.
Also, starting with Node v4, you no longer need the --harmony (now a synonym of --es_staging) flag for generators.
or you can do like this also ... but here you can execute just a single statement
user1.save().then(savedUser => console.log(`saved user: ${savedUser}`));

Resources