File size: 4,153 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# GraphQL Basics

## What is GraphQL?

GraphQL is a query language for APIs that allows clients to request exactly the data they need.

## Core Concepts

### Schema & Types
```graphql
type User {
    id: ID!
    name: String!
    email: String
    age: Int
    posts: [Post!]!
    createdAt: DateTime!
}

type Post {
    id: ID!
    title: String!
    content: String
    author: User!
    comments: [Comment!]!
}

type Query {
    user(id: ID!): User
    users(limit: Int = 10): [User!]!
    post(id: ID!): Post
}

type Mutation {
    createUser(name: String!, email: String!): User!
    updateUser(id: ID!, name: String): User!
    deleteUser(id: ID!): Boolean!
}

type Subscription {
    userCreated: User!
    postUpdated(id: ID!): Post!
}
```

### Queries
```graphql
# Fetch single user
query GetUser($id: ID!) {
    user(id: $id) {
        name
        email
        posts {
            title
        }
    }
}

# Fetch multiple users with filtering
query GetUsers($limit: Int) {
    users(limit: $limit) {
        id
        name
        email
    }
}
```

### Mutations
```graphql
mutation CreateUser($name: String!, $email: String!) {
    createUser(name: $name, email: $email) {
        id
        name
    }
}

mutation UpdatePost($id: ID!, $title: String!) {
    updatePost(id: $id, title: $title) {
        id
        title
        updatedAt
    }
}
```

### Variables
```json
{
    "id": "123",
    "name": "John",
    "email": "john@example.com"
}
```

## Implementation (Node.js + Apollo)

### Basic Server
```javascript
const { ApolloServer, gql } = require('apollo-server');
const { GraphQLScalarType, Kind } = require('graphql');

const typeDefs = gql`
    scalar DateTime
    
    type User {
        id: ID!
        name: String!
        email: String!
        createdAt: DateTime!
    }
    
    type Query {
        users: [User!]!
        user(id: ID!): User
    }
    
    type Mutation {
        createUser(name: String!, email: String!): User!
    }
    
    type Subscription {
        userCreated: User!
    }
`;

const resolvers = {
    DateTime: new GraphQLScalarType({
        name: 'DateTime',
        serialize(value) {
            return value.toISOString();
        },
        parseValue(value) {
            return new Date(value);
        }
    }),
    
    Query: {
        users: () => users,
        user: (_, { id }) => users.find(u => u.id === id),
    },
    
    Mutation: {
        createUser: (_, { name, email }) => {
            const newUser = {
                id: String(users.length + 1),
                name,
                email,
                createdAt: new Date()
            };
            users.push(newUser);
            return newUser;
        }
    }
};

const server = new ApolloServer({ typeDefs, effectors });
server.listen().then(({ url }) => {
    console.log(`Server ready at ${url}`);
});
```

### Client (React)
```javascript
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
    uri: 'http://localhost:4000/graphql',
    cache: new InMemoryCache()
});

const GET_USERS = gql`
    query GetUsers {
        users {
            id
            name
            email
        }
    }
`;

function App() {
    const { loading, error, data } = useQuery(GET_USERS);
    
    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;
    
    return (
        <div>
            {data.users.map(user => (
                <div key={user.id}>{user.name}</div>
            ))}
        </div>
    );
}
```

## GraphQL vs REST

| Feature | GraphQL | REST |
|---------|---------|------|
| Data fetching | Single request | Multiple endpoints |
| Over-fetching | No | Yes |
| Under-fetching | No | Sometimes |
| Type safety | Yes (schema) | No |
| Learning curve | Higher | Lower |
| Caching | Manual | Automatic |
| File uploads | Complex | Simple |

## Best Practices

1. **N+1 Problem** - Use DataLoader for batching
2. **Pagination** - Use cursor-based pagination
3. **Error Handling** - Return meaningful errors
4. **Security** - Implement depth limiting
5. **Performance** - Consider query cost analysis