Skip to content

Commit 4f390bb

Browse files
author
Rishabh Pandey
committed
initial commit
0 parents  commit 4f390bb

File tree

9 files changed

+309
-0
lines changed

9 files changed

+309
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules/
2+
package-lock.json/

.vscode/settings.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"git.ignoreLimitWarning": true
3+
}

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# GraphQL MongoDB Express Server
2+
3+
GraphQL server on Node using Express and connect to Mongo DB using Mongoose.
4+
5+
### Important Files and Folders
6+
7+
|File/Folder|Description|
8+
|-----------|-----------|
9+
|**index.html**| The main HTML file|
10+
|**index.js**| GraphQL Express Server|
11+
|**graphql**| Folder related to graphQL Schema.|
12+
|**model**| Folder related to Mongoose(mongodb) *Schema* and *Model*|
13+
14+
15+
* Run ``` npm start ``` to start dev mode .
16+
17+
* Once the server is up, go to browser and run http://localhost:3000/.
18+
19+
20+
## Todo
21+
22+
* Write Gulp task for build in production
23+
* use Express Middlewares (Passport , cors , multer etc .)
24+
* Use MongoDb geospatial query with graphQl
25+
* Make it CRUD .
26+
* Add more query, mutation , subscription with GrahQl.
27+

graphql/Schema/Schema.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import {
2+
GraphQLObjectType,
3+
GraphQLNonNull,
4+
GraphQLSchema,
5+
GraphQLString,
6+
GraphQLList,
7+
GraphQLInt,
8+
GraphQLBoolean
9+
} from 'graphql/type';
10+
11+
import ToDoMongo from '../../model/todo'
12+
13+
/**
14+
* generate projection object for mongoose
15+
* @param {Object} fieldASTs
16+
* @return {Project}
17+
*/
18+
export function getProjection (fieldASTs) {
19+
return fieldASTs.fieldNodes[0].selectionSet.selections.reduce((projections, selection) => {
20+
projections[selection.name.value] = true;
21+
return projections;
22+
}, {});
23+
}
24+
25+
var todoType = new GraphQLObjectType({
26+
name: 'todo',
27+
description: 'todo item',
28+
fields: () => ({
29+
itemId: {
30+
type: (GraphQLInt),
31+
description: 'The id of the todo.',
32+
},
33+
item: {
34+
type: GraphQLString,
35+
description: 'The name of the todo.',
36+
},
37+
completed: {
38+
type: GraphQLBoolean,
39+
description: 'Completed todo? '
40+
}
41+
})
42+
});
43+
44+
var schema = new GraphQLSchema({
45+
query: new GraphQLObjectType({
46+
name: 'RootQueryType',
47+
fields: {
48+
todo: {
49+
type: new GraphQLList(todoType),
50+
args: {
51+
itemId: {
52+
name: 'itemId',
53+
type: new GraphQLNonNull(GraphQLInt)
54+
}
55+
},
56+
resolve: (root, {itemId}, source, fieldASTs) => {
57+
var projections = getProjection(fieldASTs);
58+
var foundItems = new Promise((resolve, reject) => {
59+
ToDoMongo.find({itemId}, projections,(err, todos) => {
60+
err ? reject(err) : resolve(todos)
61+
})
62+
})
63+
64+
return foundItems
65+
}
66+
}
67+
}
68+
})
69+
70+
});
71+
72+
export default schema;
73+

gulpfile.babel.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import gulp from 'gulp';
2+
import gulpLoadPlugins from 'gulp-load-plugins';
3+
import path from 'path';
4+
import del from 'del';
5+
import runSequence from 'run-sequence';
6+
import babelCompiler from 'babel-core/register';
7+
import babel from 'gulp-babel';
8+
9+
const plugins = gulpLoadPlugins();
10+
11+
const paths = {
12+
js: ['./**/*.js', '!dist/**', '!node_modules/**', '!coverage/**'],
13+
nonJs: ['./package.json', './.gitignore', './**/*.ejs'],
14+
tests: './server/tests/*.js'
15+
};
16+
17+
// Clean up dist and coverage directory
18+
gulp.task('clean', () =>
19+
del(['dist/**', 'coverage/**', '!dist', '!coverage']));
20+
21+
// Set env variables
22+
gulp.task('set-env', () => {
23+
plugins.env({
24+
vars: {
25+
NODE_ENV: 'test'
26+
}
27+
});
28+
});
29+
30+
// Copy non-js files to dist
31+
gulp.task('copy', () =>
32+
gulp.src(paths.nonJs)
33+
.pipe(plugins.newer('dist'))
34+
.pipe(gulp.dest('dist')));
35+
36+
// Compile ES6 to ES5 and copy to dist
37+
gulp.task('babel', () =>
38+
gulp.src([...paths.js, '!gulpfile.babel.js'], { base: '.' })
39+
.pipe(plugins.newer('dist'))
40+
.pipe(plugins.sourcemaps.init())
41+
.pipe(babel())
42+
.pipe(plugins.sourcemaps.write('.', {
43+
includeContent: false,
44+
sourceRoot(file) {
45+
return path.relative(file.path, __dirname);
46+
}
47+
}))
48+
.pipe(gulp.dest('dist')));
49+
50+
// Start server with restart on file changes
51+
gulp.task('nodemon', ['copy', 'babel'], () =>
52+
plugins.nodemon({
53+
script: path.join('dist', 'index.js'),
54+
ext: 'js',
55+
ignore: ['node_modules/**/*.js', 'dist/**/*.js'],
56+
tasks: ['copy', 'babel']
57+
}));
58+
59+
// gulp serve for development
60+
gulp.task('serve', ['clean'], () => runSequence('nodemon'));
61+
62+
// default task: clean dist, compile js files and copy non-js files.
63+
gulp.task('default', ['clean'], () => {
64+
runSequence(['copy', 'babel']);
65+
});

index.html

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>GraphQL Express</title>
6+
</head>
7+
<body>
8+
<hr>
9+
<h1>GraphQL Server</h2>
10+
<hr>
11+
<h2>This is just a normal POST</h2>
12+
<div>Enter a new item in the text box and hit Submit to save it to the database</div>
13+
<form action="/quotes" method="POST">
14+
<input type="text" placeholder="item" name="item">
15+
<button type="submit">Submit</button>
16+
</form>
17+
<hr>
18+
<h2>GraphQL Test</h2>
19+
<hr>
20+
<div>
21+
<a href="/graphql?query={todo(itemId:1){itemId,item}}">GraphQL Test</a>
22+
</div>
23+
</body>
24+
</html>

index.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import express from 'express';
2+
import mongoose from 'mongoose';
3+
import bodyParser from 'body-parser';
4+
import ToDo from './mongoose/todo'
5+
import schema from './graphql/Schema/Schema'
6+
const app = express();
7+
8+
import {graphql} from 'graphql'
9+
import graphqlHTTP from 'express-graphql';
10+
11+
app.use(bodyParser.urlencoded({extended:true}))
12+
13+
mongoose.connect('mongodb://localhost:27017/Graphql')
14+
15+
var db = mongoose.connection;
16+
db.on('error', ()=> {console.log( 'FAILED to connect to mongoose')})
17+
db.once('open', () => {
18+
console.log( 'Connected to MongoDb')
19+
})
20+
21+
app.listen(3000,()=> {console.log("Express Server is Running @ Port -> 3000!!!")})
22+
23+
app.get('/',(req,res)=>{
24+
res.sendFile(__dirname + '/index.html')
25+
})
26+
27+
app.use('/graphql', graphqlHTTP (req => ({
28+
schema
29+
//,graphiql:true
30+
})))
31+
32+
app.post('/quotes',(req,res)=>{
33+
// Insert into TodoList Collection
34+
var todoItem = new ToDo({
35+
itemId:1,
36+
item:req.body.item,
37+
completed: false
38+
})
39+
40+
todoItem.save((err,result)=> {
41+
if (err) {console.log("---TodoItem save failed " + err)}
42+
console.log("TodoItem saved successfully "+todoItem.item)
43+
res.redirect('/')
44+
})
45+
})

model/todo.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import mongoose from 'mongoose';
2+
3+
var Schema = mongoose.Schema;
4+
5+
// create a schema
6+
var toDoSchema = new Schema({
7+
itemId: Number,
8+
item: String,
9+
completed: Boolean
10+
}, {collection:"TodoList"});
11+
12+
// the schema is useless so far
13+
// we need to create a model using it
14+
var ToDo = mongoose.model('ToDo', toDoSchema);
15+
16+
export default ToDo

package.json

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
{
2+
"name": "graphql-express",
3+
"version": "1.0.0",
4+
"description": "Graphql Express-MongoDB server",
5+
"main": "index.js",
6+
"scripts": {
7+
"start": "nodemon index.js --exec babel-node --presets es2015,stage-2",
8+
"build": "gulp",
9+
"dev": "nodemon index.js"
10+
},
11+
"dependencies": {
12+
"body-parser": "^1.15.2",
13+
"express": "^4.14.0",
14+
"express-graphql": "^0.6.1",
15+
"graphql": "^0.8.2",
16+
"mongoose": "^4.7.2"
17+
},
18+
"devDependencies": {
19+
"babel": "^6.5.2",
20+
"babel-cli": "^6.18.0",
21+
"babel-core": "^6.26.0",
22+
"babel-plugin-add-module-exports": "0.2.1",
23+
"babel-plugin-transform-runtime": "^6.23.0",
24+
"babel-preset-es2015": "^6.18.0",
25+
"babel-preset-stage-0": "^6.16.0",
26+
"babel-preset-stage-2": "6.24.1",
27+
"del": "^3.0.0",
28+
"gulp": "3.9.1",
29+
"gulp-env": "^0.4.0",
30+
"gulp-babel": "^7.0.0",
31+
"gulp-eslint": "^4.0.0",
32+
"gulp-istanbul": "1.1.2",
33+
"gulp-load-plugins": "^1.5.0",
34+
"gulp-mocha": "^4.3.1",
35+
"gulp-newer": "^1.3.0",
36+
"gulp-nodemon": "^2.2.1",
37+
"gulp-plumber": "^1.1.0",
38+
"gulp-sourcemaps": "^2.6.1",
39+
"gulp-util": "^3.0.8",
40+
"isparta": "4.0.0",
41+
"mocha": "4.0.1",
42+
"run-sequence": "^2.2.0",
43+
"nodemon": "^1.11.0"
44+
},
45+
"babel": {
46+
"presets": [
47+
"es2015",
48+
"stage-2"
49+
],
50+
"plugins": [
51+
"add-module-exports"
52+
]
53+
}
54+
}

0 commit comments

Comments
 (0)