Error: "subscription" defined in resolvers, but not in schema - javascript

index.js
const {GraphQLServer, GrphQLServer, PubSub } = require('graphql-yoga');
const db = require('./db');
const Query = require('./resolvers/Query');
const Mutation = require('./resolvers/Mutation');
const subscription = require('./resolvers/Substription')
const pubsub = new PubSub();
const typeDefs=`
type Query{
me:User!
signlevalue(name:String):String
sum(marks:[Int]):Int!
user:[User]
}
type Mutation{
createUser(id:ID,name:String,email:String):[User]
}
type User{
id:ID
name:String
email:String
age:Int
}
type Subscription{
count:Int
}
`
const resolvers={
Query,
Mutation,
subscription
}
const server= new GraphQLServer({
typeDefs,
resolvers,
context:{
db,
pubsub
}
})
server.start(()=>{
console.log('servr is running on port 4000');
})
Substription.js
const Subscription={
count:{
subscribe(parent,args,{pubsub},info){
let count=0;
setInterval(() => {
count++;
pubsub.publish('count',{
count:count
})
}, 1000);
return pubsub.asynsIterateor('count')
}
}
}
module.exports = Subscription;
package.json
{
"name": "sql",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon src/index.js --ext js,graphql --exec babel-node",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"express": "^4.17.1",
"express-graphql": "^0.11.0",
"graphql": "^15.3.0",
"graphql-yoga": "^1.18.3",
"lodash": "^4.17.20"
}
}
i am a biggner in graphQL word and i dont know what is wrong here because i have defined subsciption in schema but it still gives me error "subscription" defined in resolvers, but not in schema i have searched it but not finding any solution i am following andrew mead course from udemy

your import name is "subscription" (small s) while in your type defination you are using "Subscription"(large s)
use this
const Subscription = require('./resolvers/Substription')

Related

Why can't I connect to SQLServer uisng NodeJS?

I'm new using Node JS and now I'm creating a project that connects to SQL Server, but when I use the command node Database\connect.js It simply does do nothing, as it should do a console.log that it did connect or it didn't.
Here is my package.json
{
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"tedious": "^14.0.0"
},
"name": "weather-nodejs-apirest",
"version": "1.0.0",
"main": "connect.js",
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
And here is my connect.js
var Connection = require('tedious').Connection;
var config = {
server: 'SERVERNAME',
authentication: {
type: 'default',
options: {
userName: 'sa',
password: 'password'
}
},
options: {
database: 'weather_app',
// instanceName: 'Sqlexpress',
rowCollectionOnDone: true,
useColumnNames: false
}
}
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log(err);
} else {
console.log('Connected');
}
});
module.exports = connection;
The connection.on(...) method will not initiate the database connection itself. It only runs when the application initiates it using connection.connect() method.
Since you are exporting connection to the outside from connect.js, You should import and initiate the connection somewhere (mostly in application entry point),
const connection = require('path/to/connect.js');
// initiate
connection.connect();
Doc: http://tediousjs.github.io/tedious/getting-started.html

How to deploy with sequelize and react in heroku

This is my package.json:
{
"name": "aracelli-v-photography-website",
"version": "0.0.3",
"private": true,
"description": "a photography website",
"main": "api/server.js",
"scripts": {
"start": "concurrently -p \"{name}\" -c \"green\" -n \"database,node\" \"npx sequelize-cli db:migrate --env=production\" \"HOSTING_DIR=livebuild/ node server\"",
"dev": "concurrently -p \"{time}-{name}\" -c \"green\" -n \"react,nodemon\" \"react-scripts build\" \"nodemon server\"",
"test": "concurrently -p \"{time}-{name}\" -c \"green\" -n \"database,node\" \"DATABASE_URL=$(heroku config:get DATABASE_URL -a aracelli-v-photography) npx sequelize-cli db:migrate --env=production\" \"DATABASE_URL=$(heroku config:get DATABASE_URL -a aracelli-v-photography) node server\"",
"build": "BASE_URL=\"https://aracelli-v-photography.herokuapp.com/api\" react-scripts build && rm -rf livebuild && mv build livebuild"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Aracelli-V-Photography/aracelli-v-photography-website.git"
},
"author": "jadelynnmasker",
"license": "GPL-3.0-or-later",
"bugs": {
"url": "https://github.com/Aracelli-V-Photography/aracelli-v-photography-website/issues"
},
"homepage": "/",
"devDependencies": {
"axios": "^0.21.1",
"eslint": "^7.28.0",
"nodemon": "^2.0.7",
"prettier": "^2.3.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.4",
"react-router-dom": "^5.2.0",
"react-scripts": "^4.0.3",
"redux": "^4.1.0",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.3.0",
"uuid": "^8.3.2"
},
"dependencies": {
"bcrypt": "^5.0.1",
"concurrently": "^6.2.0",
"njwt": "^1.1.0",
"pg": "^8.6.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.6.2",
"sequelize-cli": "^6.2.0"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}My question is, why doesn't the server deploy with react
}
And my server.js:
const http = require("http");
const url = require("url");
const fs = require("fs");
const path = require("path");
const routes = require("./config/routes");
const PORT = process.env.PORT || 3000;
const HOME_DIRECTORY = process.cwd();
const STATIC_DIRECTORY = process.env.HOSTING_DIR || "build/";
const server = http.createServer(function (request, response) {
try {
process.chdir(HOME_DIRECTORY);
} catch (error) {
console.log(error);
}
if (request.url.split("/")[1] !== "api") {
const parsedUrl = url.parse(request.url);
let pathname = `.${parsedUrl.pathname}`;
const extension = path.parse(pathname).ext;
try {
process.chdir(STATIC_DIRECTORY);
} catch (error) {
return console.log(error);
}
const mapExtensionsToContentType = {
".ico": "image/x-icon",
".html": "text/html",
".js": "text/javascript",
".json": "application/json",
".css": "text/css",
".png": "image/png",
".jpg": "image/jpeg",
".wav": "audio/wav",
".mp3": "audio/mpeg",
".svg": "image/svg+xml",
".pdf": "application/pdf",
".doc": "application/msword",
};
fs.exists(pathname, function (exist) {
if (!exist) {
response.statusCode = 301;
response.setHeader("Location", "/");
return response.end(() => {
console.log(
"\nUser probably refreshed the page. Stand by for new session!"
);
});
}
if (pathname === "./") {
pathname += "index.html";
console.log("\nUser joined the site!");
}
fs.readFile(pathname, function (error, data) {
if (error) {
response.statsCode = 500;
response.end(`Error getting the file: ${error}`);
return console.error(`Error getting the file: ${error}`);
}
response.setHeader(
"Content-Type",
mapExtensionsToContentType[extension] || "text/html"
);
response.end(data);
});
});
} else {
const actionPath = `${request.method} ${request.url}`;
const route = routes.find(function (route) {
return actionPath.match(route[0]);
});
if (!route) {
return console.log(`\n${actionPath} -> undefined`);
}
console.log(`\n${actionPath} -> ${route[1]}`);
const [controllerName, method] = route[1].split("#");
const Controller = require(`./controllers/${controllerName}Controller`);
if (request.method !== "POST") {
const controller = new Controller(request, response);
controller[method]();
} else {
let body = "";
request.on("data", function (chunk) {
body += chunk.toString();
});
request.on("end", function () {
controller = new Controller(
request,
response,
JSON.parse(body)
);
controller[method]();
});
}
}
});
server.listen(PORT, function () {
console.log("Server running on port " + PORT);
});
Finally, my /src/redux/common.js, where I think the problem is:
import axiosBase from "axios";
import { v4 as uuidv4, v5 as uuidv5 } from "uuid";
export const axios = axiosBase.create({
baseURL: process.env.BASE_URL || "http://localhost:3000/api",
});
const NAMESPACE = uuidv4();
export function uuid() {
return uuidv5(uuidv4(), NAMESPACE);
}
Basically, I'm trying to host a Node.js server with more knowledge in React than in Node, and I'm stuck here because no matter what I do axios always sends requests to "http://localhost:3000/api". I need to deploy on heroku and have it send requests to heroku instead of my local machine! I looked at the docs for create-react-app and it looks like I am doing it right. I am, however, always using a production build of react because I couldn't figure out where to find the development build. Because of how it's deployed on heroku (my node server serves the react app as well as the api) I don't want my app running on two different ports and needing cors.
With that out of the way, there are basically two solutions to my problem that will make me happy. One is, I could find where the development build is and use the NODE_ENV enviromnent variable to determine whether I am on a server or not. Or, two, I could find a way to make the enviroment variables that I am using work.
Either way, I appreciate your time and consideration. If more information is needed, I will gladly post an update.
There is no problem with your app bro. You have made an error in your package.json. What you have done is include your dependencies in the devDependencies which means that react module is not being installed on your Heroku app.
During the deployment, you will notice that it shows a line pruning devDependencies which means that it's cutting the packages from the list which are in the devDependencies.
Steps to make things right:
You have to include your devDependencies in dependencies
To do so run this command
npm install axios react react-dom react-redux
react-router-dom react-scripts redux redux-devtools-extension redux-thunk uuid --save-prod
Now push your app to Heroku and it will start working.

Getting error using request-promise-native or axios in Dialogflow fulfillment inline editor

I am trying to use Request-Promise-Native or Axios but getting error during execution. I am sharing my code. I am using dialogflow inline editior. I also try with post api but not working. I guess somewhere i am doing minor mistake. Please explain also it will help me to learn.
'use strict';
const axios = require('axios');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const request = require('request-promise-native');
// this is GET api using axios
function Login(agent) {
const email = agent.parameters.email;
const password = agent.parameters.password;
const baseurl = 'http://demoapi:3000/login/buyerlogin';
var data = {"email" : email,"password": password};
return axios.get(baseurl, { params:
data})
.then(result => {
console.log(result.data);
console.log(`statusCode: ${result.statusCode}`);
agent.add(result.data);
}) }
// This Get API using Request promise native
function Login(agent) {
const email = agent.parameters.email;
const password = agent.parameters.password;
const baseurl = 'http://demoapi:3000/login/buyerlogin';
var data = {"email" : email,"password": password};
var sdata = JSON.stringify(data);
const options = {
method: 'GET',
uri: baseurl,
body: JSON.parse(sdata),
json: true
};
return request(options)
.then(result => {
console.log(result.data);
console.log(`statusCode: ${result.statusCode}`);
agent.add(result.data);
});
}
Package.json file
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "10"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.2.0",
"firebase-admin": "^5.13.1",
"firebase-functions": "^2.0.2",
"dialogflow": "^1.2.0",
"dialogflow-fulfillment": "^0.6.1",
"request": "^2.88.2",
"request-promise-native": "^1.0.9",
"axios": "^0.21.1"
}
}
Please help me out. Is anything required please let me.
Thank You

How do I use async functions in dialogflow?

I'm getting the error as "async functions' is only available in es8 (use 'esversion 8')"
I tried putting "esversion:8" in inline code, package.json but its not working out and function is not getting deployed.
Code:
index.js
'use strict';
'use esversion: 8'; //not working
async function getWeather() {
const city = 'Mumbai';
const OPENWEATHER_API_KEY = '<API KEY>';
const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${OPENWEATHER_API_KEY}`);
const data = await response.json();
console.log(data);
const { main } = data;
const { temp } = main;
const kelvin = temp;
const celsius = Math.round(kelvin - 273.15);
console.log(celsius);
}
Code package.json
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "8"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.2.0",
"firebase-admin": "^5.13.1",
"firebase-functions": "^2.0.2",
"dialogflow": "^0.6.0",
"dialogflow-fulfillment": "^0.5.0",
"esversion":"8" //not working
}
}
Error Screenshot
Is there any solution to this or any other way?

TypeError: sql.Connection is not a function Node.js

I am very beginner with node.js and javscript itself. I am trying to establish a basic connection to SQLServer but I am getting the following error:
TypeError: sql.Connection is not a function
I am following the recommendations of the mssql package git repository
//get an instance of sqlserver
var sql = require('mssql');
//set up a sql server credentials
var config = {
server: 'localhost',
database: 'trafiyadb',
user: 'jhonycage',
password: 'juan1014',
port: 1433
};
function con() {
var dbConn = new sql.Connection(config);
dbConn.connect().then(function(){
console.log("connected")
}).catch(function (err) {
console.log(err);
})
}
con();
and this is the package.json
{
"name": "trafiyaapi",
"version": "1.0.0",
"description": "",
"main": "server.js\u001b[A\u001b[B\u001b[B\u001b[B\u001b[A\u001b[B",
"dependencies": {
"express": "^4.15.2",
"body-parser": "^1.17.1",
"mssql": "^4.0.4",
"jsonwebtoken": "^7.4.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC"
}
I am just executing
$node server
I must be doing something wrong, how can i connect to database?
In fact, the function Connection doesn't exist. According to the documentation, to connect to a database, you can use the class ConnectionPool, or the method connect.
var dbConn = new sql.ConnectionPool(config);
dbConn.connect(function(err) {
// ...
});
// OR ...
sql.connect(config).then(function(dbConn) {
// ...
})

Categories