GraphQL - node - Apollo - mongoDB
-
Back-End
index.js
// import necessary libs and resourses
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { mongoose, Schema, model } from 'mongoose';
// define global async function
const startServer = async () => {
try {
// connect with mongoDB database
await mongoose.connect(URL_API, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// define Schemas that I'm gonna use
const bookSchema = new Schema({
title: String,
author: {
type: Schema.Types.ObjectId,
ref: 'Author',
},
});
const authorSchema = new Schema({
name: String,
booksByAuthor: [{
type: Schema.Types.ObjectId,
ref: 'Book',
}],
});
const Book = model('Book', bookSchema, 'my_books_collection');
const Author = model('Author', authorSchema, 'my_authors_collection');
const typeDefs = `
type Book {
title: String
author: Author
}
type Author {
name: String
booksByAuthor: [Book]
}
type Query {
books: [Book]
authors: [Author]
}
`;
const resolvers = {
Query: {
books: async () => {
const books = await Book.find();
return books;
},
authors: async () => {
const authors = await Author.find();
return authors;
},
},
Author: {
booksByAuthor: async (parent) => {
if (typeof parent._id === 'object') {
const books = await Book.find({ author: parent._id });
return books;
} else {
const books = await Book.find({ author: parent.name });
return books;
}
},
},
Book: {
author: async (parent) => {
if (typeof parent.author === 'object') {
const authors = await Author.find({ _id: parent.author });
return authors[0]; // Since it's a single author
} else {
const authors = await Author.find({ name: parent.author });
return authors[0]; // Since it's a single author
}
},
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
});
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
});
console.log(`🚀 Server ready at: ${url}`);
} catch (error) {
console.error('Error starting server:', error.message);
}
};
startServer();
reference: https://www.youtube.com/watch?v=5199E50O7SI