Skip to content

Commit 5d870a7

Browse files
author
Ryan Christiani
committed
Adding query option
1 parent 772a619 commit 5d870a7

File tree

4 files changed

+58
-12
lines changed

4 files changed

+58
-12
lines changed

schemas/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@ mongoose.Promise = Promise;
55
mongoose.connect("mongodb://localhost/notesql");
66

77
module.exports = {
8-
note: require('./note.js')
8+
note: require('./note.js').Note,
9+
graphQLNote: require('./note.js').graphQlNote
910
};

schemas/note.js

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,55 @@
11
const mongoose = require('mongoose');
22
const Schema = mongoose.Schema;
3+
const graphql = require('graphql');
34

45
const noteSchema = new Schema({
56
title: String,
67
body: String,
78
created_at: {
89
default: Date.now,
9-
type: Date
10+
type: Number
1011
}
1112
});
1213

1314
const Note = mongoose.model("Note", noteSchema);
1415

15-
module.exports = Note;
16+
const NoteType = new graphql.GraphQLObjectType({
17+
name: "Note",
18+
fields: {
19+
title: {
20+
type: graphql.GraphQLString
21+
},
22+
body: {
23+
type: graphql.GraphQLString
24+
},
25+
created_at: {
26+
type: graphql.GraphQLInt
27+
}
28+
}
29+
});
30+
31+
const QueryType = new graphql.GraphQLObjectType({
32+
name: "Query",
33+
fields: {
34+
notes : {
35+
type: new graphql.GraphQLList(NoteType),
36+
resolve() {
37+
return new Promise((resolve,reject) => {
38+
Note.find({},(err,docs) => {
39+
if(err) {
40+
reject(err);
41+
}
42+
resolve(docs);
43+
});
44+
});
45+
}
46+
}
47+
}
48+
});
49+
50+
module.exports = {
51+
Note,
52+
graphQlNote: new graphql.GraphQLSchema({
53+
query: QueryType
54+
})
55+
};

server.js

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,14 @@
11
const express = require('express');
22
const app = express();
3-
const { note } = require('./schemas');
3+
const { note, graphQLNote } = require('./schemas');
44
const graphqlHTTP = require('express-graphql');
55
const bodyParser = require('body-parser');
6+
const { handleError } = require('./utils');
7+
68

79
app.use(bodyParser.json());
810
app.use(express.static("./public/"));
911

10-
function handleError(err,res) {
11-
res.status(400)
12-
.send({
13-
error: err
14-
});
15-
return;
16-
}
17-
1812
app.get('/api/notes',(req,res) => {
1913
note.find({},{__v: 0},(err,docs) => {
2014
if(err) {
@@ -65,4 +59,6 @@ app.delete('/api/notes/:id', (req,res) => {
6559
});
6660
});
6761

62+
app.use('/api/graphql/notes', graphqlHTTP({schema: graphQLNote}));
63+
6864
app.listen('3500');

utils.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module.exports = {
2+
handleError(err,res) {
3+
res.status(400)
4+
.send({
5+
error: err
6+
});
7+
return;
8+
}
9+
}

0 commit comments

Comments
 (0)