I am having an error with mongoose.
This is my code
const { ApolloServer } = require("apollo-server");
const gql = require("graphql-tag");
const mongoose = require("mongoose");
const { MONGODB } = require("./config");
const typeDefs = gql `
type Query {
sayHi: String!
}
`;
const resolvers = {
Query: {
sayHi: () => "Hello from GraphQL",
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
mongoose
.connect(MONGODB, {
useNewUrlParser: true,
})
.then(() => {
console.log("Connection to Db established sucessfully!");
return server.listen({
port: 5000,
});
})
.then((res) => {
console.log(`Server running at ${res.url}`);
});
And I am getting this error on bash.
The use of Unhandled Promise Rejection is deprecated. The next time node's will exit with an exit code of non-zero.
Can someone please tell me how to solve it with a code example.
I think the error is in the mongoose.connect(()) line.
Related
I have been following the www.howtographql.com tutorials but i am stuck as i am not able to add authorization token in http headers. As soon as i write the authorization token it gives an error - 'Server cannot be reached'
index.js
const { ApolloServer } = require('apollo-server');
const { PrismaClient } = require('#prisma/client');
const fs = require('fs');
const path = require('path');
const { getUserId } = require('./utils');
const Query = require('./resolvers/Query');
const Mutation = require('./resolvers/Mutation');
const User = require('./resolvers/User');
const Link = require('./resolvers/Link');
const prisma = new PrismaClient();
const resolvers = {
Query,
Mutation,
User,
Link
}
const server = new ApolloServer({
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf-8'
),
resolvers,
context:({ req }) => {
return {
...req,
prisma,
userId: req && req.headers.authorization ? getUserId(req) : null
};
}
});
server.listen()
.then(({ url }) => console.log(`Server is running on ${url}`)
);
I was working with a NodeJS project and I got an error after declaring a class.
const { MongoClient } = require("mongodb");
const { EventEmitter } = require("events");
class DbConnection extends EventEmitter{
mongoClient = new MongoClient(
"mongodb+srv://xxxx:xxxx#xxxx.xxxx.mongodb.net/xxxx?retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true }
);
getConnection(){
this.mongoClient.connect((err, mongodb) => {
console.log(mongoClient);
if (err) throw err;
this.emit("dbConnection", {
db: this.mongoClient.db("passport")
});
DbConnection.setInstance(mongodb);
});
}
static setInstance(mongodb){
DbConnection.db = mongodb.db("passport");
DbConnection.userCollection = DbConnection.db.collection("user");
}
}
module.exports = DbConnection;
The error is at line 6 of this file (mongoClient = new MongoClient). The error is:
mongoClient = new MongoClient(
^
SyntaxError: Unexpected token =
I don't understand the reason considering that in another project I used the same code and it works.
Any solution? Tnx
Use mongoose instead
const mongoose = require('mongoose');
module.exports = () => new Promise((resolve, reject) => {
const { dbhost, dbuser, dbpass, dbname, dbport } = process.env;
let connection_url = `mongodb://${dbuser}:${encodeURIComponent(dbpass)}#${dbhost}:${dbport}/${dbname}`
mongoose
.connect(connection_url, { useNewUrlParser: true, useUnifiedTopology: true
})
.then(async () => {
winston.info(`Connected to ${connection_url} ...`);
mongoose.set('debug', true);
resolve();
}).catch(reject);
})
It is worked for me.
I don't get the request variable in the mutation GraphQL on the backend. I don't understand why it doesn't work.
I get the next error:
"Cannot destructure property 'name' of 'undefined' as it is undefined."
That mutation I make in Apollo Studio:
mutation Mutation($createOwnerName: String) {
createOwner(name: $createOwnerName)
}
My variables in Apollo Studio:
{
"createOwnerName": "John"
}
My backend with Express
schema.js:
const { buildSchema } = require("graphql");
const schema = buildSchema(`
type Mutation {
createOwner(name: String): String
}
`);
module.exports = schema;
resolvers.js:
const resolvers = {
Mutation: {
createOwner: ({name}) => {
console.log('createOwner name', name)
return name
}
}
}
server.js:
const { createServer } = require("http");
const express = require("express");
const { execute, subscribe } = require("graphql");
const { ApolloServer } = require("apollo-server-express");
const { SubscriptionServer } = require("subscriptions-transport-ws");
const { makeExecutableSchema } = require("#graphql-tools/schema");
const typeDefs = require("./graphql/schema.js");
const resolvers = require("./graphql/resolvers.js");
require("dotenv").config();
const mongoose = require("mongoose");
// mongoose
mongoose
.connect(process.env.DB_HOST, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
(async () => {
const PORT = 3033;
const app = express();
const httpServer = createServer(app);
app.get("/rest", function (req, res) {
return res.json({ data: "rest" });
});
const schema = makeExecutableSchema({ typeDefs, resolvers });
const server = new ApolloServer({
schema,
});
await server.start();
server.applyMiddleware({ app });
SubscriptionServer.create(
{ schema, execute, subscribe },
{ server: httpServer, path: server.graphqlPath }
);
httpServer.listen(PORT, () => {
console.log(
`🚀 Query endpoint ready at http://localhost:${PORT}${server.graphqlPath}`
);
console.log(
`🚀 Subscription endpoint ready at ws://localhost:${PORT}${server.graphqlPath}`
);
});
})();
You are destructuring the wrong argument. Arguments are in that order:
Parent value
Argument values
Context
GraphQL Resolve Info
Destructure the second parameter:
const resolvers = {
Mutation: {
createOwner: (parent, {name}) => {
console.log('createOwner name', name)
return name
}
}
}
I'm trying to set up an apollo server and an error shows up.
import { createConnection } from "typeorm";
import { Post } from "./entity/Post";
const express = require("express");
import { buildSchema } from "type-graphql";
import { ApolloServer } from "apollo-server-express";
import { PostResolver } from "./Resolvers/post";
createConnection()
.then(async (connection) => {
console.log("Inserting a new user into the database...");
const post = new Post();
post.firstName = "Timber";
post.lastName = "Saw";
post.age = 25;
await connection.manager.save(post);
console.log("Saved a new user with id: " + post.id);
console.log("Loading users from the database...");
const posts = await connection.manager.find(Post);
console.log("Loaded users: ", posts);
const app = express();
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Listening on PORT: ${PORT}`));
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [PostResolver],
}),
});
await apolloServer.start();
apolloServer.applyMiddleware({ app });
})
.catch((error) => console.log(error));
[ERROR] 16:49:21 ⨯ Unable to compile TypeScript:
src/index.ts:27:43 - error TS2345: Argument of type '{ schema: GraphQLSchema; }' is not assignable to parameter of type 'Config'.
Type '{ schema: GraphQLSchema; }' is missing the following properties from type 'Config': formatError, debug, rootValue, validationRules, and 6 more.
I've tried installing dependencies again, changed TypeScript config, restarting the whole project but nothing seems to fix the problem. Any clue?
I am trying to get a subscription up and running with ApolloServer (v 2.2.2). I had a setup that all-of-a-sudden just stopped working. When I try to connect to the subscription in graphiql/PlaygroundI get the error:
{
"error": "Could not connect to websocket endpoint ws://localhost:4000/graphql. Please check if the endpoint url is correct."
}
As I have rest-endpoints in my app I need to have express but I can't get the minimal example from below running:
import http from 'http';
import { ApolloServer, PubSub } from 'apollo-server-express';
import express from 'express';
const pubsub = new PubSub();
// The DB
const messages = [];
const typeDefs = `
type Query {
messages: [String!]!
}
type Mutation {
addMessage(message: String!): [String!]!
}
type Subscription {
newMessage: String!
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
`;
const resolvers = {
Query: {
messages() {
return messages;
}
},
Mutation: {
addMessage(root, { message }) {
let entry = JSON.stringify({ id: messages.length, message: message });
messages.push(entry);
pubsub.publish('newMessage', { entry: entry });
return messages;
},
},
Subscription: {
newMessage: {
resolve: (message) => {
return message.entry;
},
subscribe: () => pubsub.asyncIterator('newMessage'),
},
},
};
const app = express();
const PORT = 4000;
const server = new ApolloServer({
typeDefs,
resolvers,
subscriptions: {
onConnect: () => console.log('Connected to websocket'),
}
});
server.applyMiddleware({ app })
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);
httpServer.listen(PORT, () => {
console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
console.log(`🚀 Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
})
The other endpoints work fine but it is unable to create the WebSocket. As far as I understand it I shouldn't have to use a different server or port (see https://www.ably.io/concepts/websockets). I've tinkered with SubsciptionServer but this should be handled by installSubscriptionHandlers (here's the code).
The it turns out that Firefox has issues with websockets (see this bug report that has been re-appeared even after the supposed fix).
In Firefox it works directly after starting a novel browser but after some hot reloading it stops working. The following helps out with starting out fresh but not with the reloading issue:
const wsLink = new WebSocketLink({
uri: SUBSCRIPTION_URI,
options: {
reconnect: true,
timeout: 20000,
lazy: true,
},
});
window.addEventListener('beforeunload', () => {
// #ts-ignore - the function is private in typescript
wsLink.subscriptionClient.close();
});
I think the bug is related to this SO-question: "websocket was interrupted while page is loading" on Firefox for Socket.io
If you want to test different solutions I've created an example repo: https://github.com/gforge/subscription_example that works both by itself and with a Docker container.
A lot of time has passed and now I faced with the same problem and I found a solution.
import { createServer } from 'http';
const app = express();
const server = new ApolloServer({});
server.applyMiddleware({ app });
const httpServer = createServer(app);
server.installSubscriptionHandlers(httpServer);
server.listen()
Works for me