Skip to content

Instantly share code, notes, and snippets.

@sahilrajput03
Last active October 22, 2020 18:15
Show Gist options
  • Save sahilrajput03/c369decca72c9d01acc5b72c6f8f5430 to your computer and use it in GitHub Desktop.
Save sahilrajput03/c369decca72c9d01acc5b72c6f8f5430 to your computer and use it in GitHub Desktop.
mongoose with graphql #graphql #mongoose #mongodb
const { v1: uuid } = require("uuid");
const { ApolloServer, gql, UserInputError } = require("apollo-server");
const mongoose = require("mongoose");
// const { books, authors } = require("./data");
//models of collections in mongodb
const BookSchema = require("./models/bookSchema");
const AuthorSchema = require("./models/authorSchema");
mongoose.set("useFindAndModify", false);
const MONGODB_URI = "mongodb://localhost/admin"; //mu localcally running db
mongoose.set("useCreateIndex", true);
console.log("connecting to", MONGODB_URI);
mongoose
.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("connected to MongoDB");
})
.catch((error) => {
console.log("error connection to MongoDB:", error.message);
});
// Code for once to load, or delete all document in db.
// Book.collection.deleteMany({});
// Author.collection.deleteMany({});
// Book.collection.insertMany(books);
// Author.collection.insertMany(authors);
const typeDefs = gql`
type Author {
name: String
born: Int
}
type Book {
title: String!
author: Author
published: Int!
genres: [String!]
id: ID!
}
type allAuth {
name: String
bookCount: Int
born: Int
}
type Query {
bookCount: Int!
authorCount: Int!
allBooks(author: String, genre: String): [Book!]!
allAuthors: [allAuth]
}
type Mutation {
addBook(title: String!, author: String, published: Int, genres: [String]!): Book
editAuthor(name: String!, setBornTo: Int): Author
}
`;
const resolvers = {
Query: {
bookCount: () => books.length,
authorCount: () => authors.length,
allBooks: async (root, args) => {
const books = await BookSchema.find({});
console.log("bookksss-", books);
if (args.author) {
return books.filter((b) => b.author == args.author);
} else if (args.genre) {
return books.filter((b) => b.genres.includes(args.genre));
} else {
return books;
}
},
allAuthors: async () => {
const authors = await AuthorSchema.find({});
// console.log(await Author.find({}));
const books = await BookSchema.find({});
// console.log("aaltu-", books);
return authors.map((auth) => ({
name: auth.name,
bookCount: books.filter((b) => b.author == auth.name).length,
born: auth.born,
}));
},
},
Mutation: {
addBook: async (root, args) => {
console.log('i"m executing.... '); // THIS IS NOT GETTING EXECUTED..whY//?
console.log("$args:-", args);
const books = await BookSchema.find({});
// const books = await BookSchema.find({}).populate("author");
if (books.find((p) => p.title === args.title)) {
throw new UserInputError("Title must be unique", {
invalidArgs: args.title,
});
}
// const book = { ...args, id: uuid() };
const newAuthor = await new AuthorSchema({ name: args.author, born: Number(0) }).save();
console.log("newauthor.id", newAuthor.id);
const book = { ...args, author: newAuthor };
try {
delete args.author;
const bookSaved = await new BookSchema({ ...book }).save();
console.log("☻==user saved succesfully==");
return bookSaved;
} catch (error) {
console.log("♣==error occured while saving==");
return error.message;
}
//#region
// console.log("$person:-", person);
// if (true) {
// // console.log(
// // "$authors.find(args.author)",
// // authors.find((item) => item == args.author)
// // );
// authors.push({ name: args.author, id: uuid() });
// }
// // books = books.concat(book);
//#endregion
},
editAuthor: (root, args) => {
const toEdit = authors.find((a) => a.name == args.name);
console.log("$toEdit:-", toEdit);
if (!toEdit) {
return null;
}
const edited = { ...toEdit, born: args.setBornTo };
authors = authors.map((a) => (a.name === args.name ? edited : a));
return edited;
},
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.listen({ port: 4001 }).then(({ url }) => {
console.log(`Server ready at ${url}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment