-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (79 loc) · 2.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const express = require('express')
const jwt = require("express-jwt")
const jsonwebtoken = require("jsonwebtoken")
const bcrypt = require("bcryptjs")
const mongoose = require('mongoose')
const { User } = require('./models/User.js')
const { ApolloServer, gql } = require('apollo-server-express')
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type User {
id: Int
username: String!
email: String!
password: String!
}
type Query {
me: User
}
type Mutation {
signup (username: String!, email: String!, password: String!): String
login (email: String!, password: String!): String
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
me: () => 'Hello world!',
},
Mutation: {
async signup(_, { username, email, password }) {
let user = new User({
username,
email,
password: await bcrypt.hash(password, 10)
});
await user.save((err) => {
if (err) {
console.error(err);
// apollo error.
}
});
// Return json web token
return jsonwebtoken.sign(
{ id: user.id, email: user.email },
"process.env.JWT_SECRET",
{ expiresIn: '1y' }
);
},
async login(_, { email, password }) {
const user = await User.findOne({ email: email })
if (!user) {
throw new Error('No user with that email')
}
const valid = await bcrypt.compare(password, user.password)
if (!valid) {
throw new Error('Incorrect password')
}
// Return json web token
return jsonwebtoken.sign(
{ id: user.id, email: user.email },
"process.env.JWT_SECRET",
{ expiresIn: '1y' }
)
}
}
};
mongoose.connect('mongodb://valon:[email protected]:25331/caradmindb');
const server = new ApolloServer({ typeDefs, resolvers });
// auth middleware
const auth = jwt({
secret: "process.env.JWT_SECRET",
credentialsRequired: false
});
const app = express();
app.use(auth);
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);