Skip to content

Instantly share code, notes, and snippets.

@tithi021
Last active November 14, 2017 18:08
Show Gist options
  • Save tithi021/3403d2029804f286338c78212350a4a9 to your computer and use it in GitHub Desktop.
Save tithi021/3403d2029804f286338c78212350a4a9 to your computer and use it in GitHub Desktop.
GraphQL APIs CRUD By NodeJs, MongoDB, Express, Angular5
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ModalModule } from 'ngx-bootstrap/modal';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
// Apollo
import { GraphQLModule } from './graphql.module';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule, // provides HttpClient for HttpLink
GraphQLModule, // Import GraphQLModule
FormsModule,
ModalModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<ng-template #template>
<div class="modal-header">
<h4 class="modal-title pull-left">Create New User</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">User Name</label>
<input type="text" class="form-control" name="name" placeholder="Name" [(ngModel)]="name">
</div>
<button type="button" class="btn btn-default" *ngIf="!user.id" (click)="createUser(name);">Create</button>
<button type="button" class="btn btn-default" *ngIf="user.id" (click)="updateUser(name);">Update</button>
</form>
</div>
</ng-template>
createUser(value) {
this.apollo
.mutate({
mutation: Query.addUser,
variables: {
name: value
},
update: (proxy, { data: { addUser } }) => {
// Read the data from our cache for this query.
const data: any = proxy.readQuery({ query: Query.Users });
data.users.push(addUser);
// Write our data back to the cache.
proxy.writeQuery({ query: Query.Users, data });
}
})
.subscribe(({ data }) => {
this.closeFirstModal(); // Close Modal
}, (error) => {
console.log('there was an error sending the query', error);
});
}
var GraphQLSchema = require('graphql').GraphQLSchema;
var GraphQLObjectType = require('graphql').GraphQLObjectType;
var queryType = require('./queries/user').queryType;
var mutation = require('./mutations/index');
exports.userSchema = new GraphQLSchema({
query: queryType,
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: mutation
})
})
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
// Apollo
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
// const uri = 'http://localhost:4000/graphql'; // Development
const uri = 'https://graphql-crud-server.herokuapp.com/graphql'; // Production
@NgModule({
exports: [
HttpClientModule,
ApolloModule,
HttpLinkModule
]
})
export class GraphQLModule {
constructor(
apollo: Apollo,
httpLink: HttpLink
) {
// create Apollo
apollo.create({
link: httpLink.create({ uri }),
cache: new InMemoryCache()
});
}
}
var GraphQLNonNull = require('graphql').GraphQLNonNull;
var GraphQLString = require('graphql').GraphQLString;
var UserType = require('../types/user');
var UserModel = require('../../models/user');
exports.add = {
type: UserType.userType,
args: {
name: {
type: new GraphQLNonNull(GraphQLString),
}
},
resolve(root, params) {
const uModel = new UserModel(params);
const newUser = uModel.save();
if (!newUser) {
throw new Error('Error');
}
return newUser
}
}
var addUser = require('./add').add;
var removeUser = require('./remove').remove;
var updateUser = require('./update').update;
module.exports = {
addUser,
removeUser,
updateUser
}
var GraphQLNonNull = require('graphql').GraphQLNonNull;
var GraphQLString = require('graphql').GraphQLString;
var UserType = require('../types/user');
var UserModel = require('../../models/user');
exports.remove = {
type: UserType.userType,
args: {
id: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve(root, params) {
const removeduser = UserModel.findByIdAndRemove(params.id).exec();
if (!removeduser) {
throw new Error('Error')
}
return removeduser;
}
}
var GraphQLNonNull = require('graphql').GraphQLNonNull;
var GraphQLString = require('graphql').GraphQLString;
var UserType = require('../types/user');
var UserModel = require('../../models/user');
exports.update = {
type: UserType.userType,
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLString)
},
name: {
type: new GraphQLNonNull(GraphQLString),
}
},
resolve(root, params) {
return UserModel.findByIdAndUpdate(
params.id,
{ $set: { name: params.name } },
{ new: true }
)
.catch(err => new Error(err));
}
}
var GraphQLObjectType = require('graphql').GraphQLObjectType;
var GraphQLList = require('graphql').GraphQLList;
var UserModel = require('../../models/user');
var userType = require('../types/user').userType;
// Query
exports.queryType = new GraphQLObjectType({
name: 'Query',
fields: function () {
return {
users: {
type: new GraphQLList(userType),
resolve: function () {
const users = UserModel.find().exec()
if (!users) {
throw new Error('Error')
}
return users
}
}
}
}
});
var GraphQLObjectType = require('graphql').GraphQLObjectType;
var GraphQLNonNull = require('graphql').GraphQLNonNull;
var GraphQLID = require('graphql').GraphQLID;
var GraphQLString = require('graphql').GraphQLString;
// User Type
exports.userType = new GraphQLObjectType({
name: 'user',
fields: function () {
return {
id: {
type: new GraphQLNonNull(GraphQLID)
},
name: {
type: GraphQLString
}
}
}
});
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Name</th>
<th class="text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users; let i = index">
<td>{{ i+1 }}</td>
<td>{{ user.name }}</td>
<td>
<!-- Show Edit User Form -->
<button class="btn btn-info" (click)="showEditUserForm(user, template)">
<i class="fa fa-edit"></i>
</button>
<!-- Remove User -->
<button class="btn btn-danger" (click)="removeUser(user.id)">
<i class="fa fa-minus"></i>
</button>
</td>
</tr>
</tbody>
</table>
getUsers() {
this.apollo.watchQuery({ query: Query.Users })
.valueChanges
.map((result: any) => result.data.users).subscribe((data) => {
this.users = data;
})
}
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: {
type: String,
required: true
}
});
var Model = mongoose.model('User', userSchema);
module.exports = Model;
removeUser(id) {
this.apollo
.mutate({
mutation: Query.removeUser,
variables: {
id: id
},
update: (proxy, { data: { removeUser } }) => {
// Read the data from our cache for this query.
const data: any = proxy.readQuery({ query: Query.Users });
var index = data.users.map(function (x) { return x.id; }).indexOf(id);
data.users.splice(index, 1);
// Write our data back to the cache.
proxy.writeQuery({ query: Query.Users, data });
}
})
.subscribe(({ data }) => {
console.log(data)
}, (error) => {
console.log('there was an error sending the query', error);
});
}
const express = require("express");
const mongoose = require('./config/mongoose');
const graphqlHTTP = require("express-graphql");
const cors = require("cors");
const db = mongoose();
const app = express();
app.use('*', cors());
const userSchema = require('./graphql/index').userSchema;
app.use('/graphql', cors(), graphqlHTTP({
schema: userSchema,
rootValue: global,
graphiql: true
}));
// Up and Running at Port 4000
app.listen(process.env.PORT || 4000, () => {
console.log('A GraphQL API running at port 4000');
});
updateUser(user) {
this.apollo
.mutate({
mutation: Query.updateUser,
variables: {
id: this.user.id,
name: user
},
update: (proxy, { data: { updateUser } }) => {
// Read the data from our cache for this query.
const data: any = proxy.readQuery({ query: Query.Users });
var index = data.users.map(function (x) { return x.id; }).indexOf(this.user.id);
data.users[index].name = user;
// Write our data back to the cache.
proxy.writeQuery({ query: Query.Users, data });
}
})
.subscribe(({ data }) => {
this.closeFirstModal();
}, (error) => {
console.log('there was an error sending the query', error);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment