๐Ÿ“ฆ lucavehbiu / playpals_backend

๐Ÿ“„ server.js ยท 64 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Your GraphQL schema - the blueprint of your data structure
const typeDefs = gql`
  type Match {
    id: ID!
    title: String!
    date: String!
    location: String!
    currentPlayers: Int!
    maxPlayers: Int!
  }

  type Query {
    matches: [Match!]!
    match(id: ID!): Match
  }

  type Mutation {
    createMatch(title: String!, date: String!, location: String!, maxPlayers: Int!): Match!
  }
`;

// In-memory database - your temporary data sanctuary
let matches = [];

// Resolvers - the logic behind your GraphQL operations
const resolvers = {
  Query: {
    matches: () => matches,
    match: (_, { id }) => matches.find(m => m.id === id),
  },
  Mutation: {
    createMatch: (_, { title, date, location, maxPlayers }) => {
      const match = {
        id: String(matches.length + 1),
        title,
        date,
        location,
        maxPlayers,
        currentPlayers: 0
      };
      matches.push(match);
      return match;
    },
  },
};

async function startApolloServer() {
  const server = new ApolloServer({ typeDefs, resolvers });
  await server.start();

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

  const PORT = 4000;
  app.listen(PORT, () => {
    console.log(`๐Ÿš€ Server ready at http://localhost:${PORT}${server.graphqlPath}`);
  });
}

startApolloServer();