DeveloperBreeze

Graphql Development Tutorials, Guides & Insights

Unlock 2+ expert-curated graphql tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your graphql skills on DeveloperBreeze.

Tutorial
javascript nodejs +1

Building a GraphQL API with Node.js and Apollo Server

const { ApolloServer, gql, PubSub } = require('apollo-server-express');
const pubsub = new PubSub();

const BOOK_ADDED = 'BOOK_ADDED';

const typeDefs = gql`
    type Book {
        title: String!
        author: String!
    }

    type Query {
        books: [Book]
    }

    type Mutation {
        addBook(title: String!, author: String!): Book
    }

    type Subscription {
        bookAdded: Book
    }
`;

const resolvers = {
    Query: {
        books: () => books,
    },
    Mutation: {
        addBook: (_, { title, author }) => {
            const newBook = { title, author };
            books.push(newBook);
            pubsub.publish(BOOK_ADDED, { bookAdded: newBook });
            return newBook;
        },
    },
    Subscription: {
        bookAdded: {
            subscribe: () => pubsub.asyncIterator([BOOK_ADDED]),
        },
    },
};

const server = new ApolloServer({
    typeDefs,
    resolvers,
    subscriptions: {
        path: '/subscriptions',
    },
});

const app = express();
server.applyMiddleware({ app });

const httpServer = require('http').createServer(app);
server.installSubscriptionHandlers(httpServer);

httpServer.listen({ port: 4000 }, () => {
    console.log(` Server ready at http://localhost:4000${server.graphqlPath}`);
    console.log(` Subscriptions ready at ws://localhost:4000${server.subscriptionsPath}`);
});

In the GraphQL Playground, you can test the subscription by running the following:

Aug 12, 2024
Read More
Code
nodejs graphql

GraphQL API Server with Node.js and Apollo Server

     mutation {
       addBook(title: "1984", author: "George Orwell") {
         title
         author
       }
     }
  • Flexible Queries: Allows clients to request only the data they need, reducing over-fetching.
  • Strongly Typed: Ensures data consistency and helps with error handling.
  • Single Endpoint: All data operations occur through a single endpoint, simplifying network requests.

Aug 12, 2024
Read More