-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial-script.js
More file actions
95 lines (78 loc) · 2.52 KB
/
tutorial-script.js
File metadata and controls
95 lines (78 loc) · 2.52 KB
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
// Welcome to Launchpad!
// Log in to edit and save pads, run queries in GraphiQL on the right.
// Click "Download" above to get a zip with a standalone Node.js server.
// See docs and examples at https://github.com/apollographql/awesome-launchpad
// graphql-tools combines a schema string with resolvers.
import { graphql, buildSchema } from 'graphql';
import { makeExecutableSchema } from 'graphql-tools';
import { MongoClient, ObjectID, Db } from 'mongodb';
function fromMongo(item) {
return {
...item,
id: item._id.toString(),
};
};
function toMongo(item) {
return {
...item,
_id: ObjectID(item.id)
};
}
// Construct a schema, using GraphQL schema language
const typeDefs = `
type Query {
hello: String!
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
hello: async (parent, input, context) => {
return "Hello World";
}
}
};
async function getAuthorByName(name, mongo) {
return mongo.collection('authors').find({ name: name }).map(fromMongo).toArray();
}
async function getAuthorsByIds(ids, mongo) {
var mapped = ids.map(id => new ObjectID(id));
return mongo.collection('authors').find({ _id: { $in: mapped } }).map(fromMongo).toArray();
}
async function getPostByTitle(title, mongo) {
return mongo.collection('posts').find({ title: title }).map(fromMongo).toArray();
}
async function insertAuthor(author, mongo) {
var result = await mongo.collection('authors').insertOne(author);
return fromMongo(await mongo.collection('authors').findOne({ _id: result.insertedId }))
}
async function insertPost(post, mongo) {
var result = await mongo.collection('posts').insertOne(post);
return fromMongo(await mongo.collection('posts').findOne({ _id: result.insertedId }))
}
async function deleteAuthor(id, mongo) {
return mongo.collection('authors').deleteOne({ _id: new ObjectID(id) }).ok;
}
async function deletePost(id, mongo) {
return mongo.collection('posts').deleteOne({ _id: new ObjectID(id) }).ok;
}
async function getAuthors(mongo) {
return mongo.collection('authors').find({}, {}).map(fromMongo).toArray();
}
async function getPosts(mongo) {
return mongo.collection('posts').find({}, {}).map(fromMongo).toArray();
}
export const schema = makeExecutableSchema({
typeDefs,
resolvers
})
let mongo;
export async function context(headers, secrets) {
if (!mongo) {
var result = await MongoClient.connect("mongodb+srv://std:lOD2z6A9PhX6eMOf@eportfolio-e6yzb.mongodb.net/eportfolio")
mongo = result.db('eportfolio')
}
return {
mongo
};
}