# How to Create a GraphQL Server with NestJS and TypeScript?

### What is **GraphQL API Design?**

GraphQL, a query language for APIs, revolutionizes data fetching and manipulation with its robustness and clarity when combined with [TypeScript](https://www.typescriptlang.org/), a statically typed superset of JavaScript.

## GraphQL as a new API design paradigm.

GraphQL offers a flexible, efficient approach to data interaction, allowing clients to request specific information using a single endpoint. Its schema-driven approach allows for data structures, relationships, and operations, enabling front-end developers to control data queries and minimize over-fetching or under-fetching.

### Create a small example of GraphQL as a new API design paradigm.

We'll use Node.js and Express to construct a simple GraphQL server, and we'll create a schema for querying and updating book data. [TypeScript](https://www.w3schools.com/typescript/typescript_intro.php) will also be used to ensure type safety.

### Step 1: Install the required packages

```bash
npm init -y
npm install express express-graphql graphql
```

### Step 2: Set up the server and GraphQL schema

```typescript
//index.ts
import express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';

const app = express();

const BookType = new GraphQLObjectType({
  name: 'Book',
  fields: () => ({
    title: { type: GraphQLString },
    author: { type: GraphQLString },
  }),
});

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    book: {
      type: BookType,
      args: {
        title: { type: GraphQLString },
      },
      resolve(parent, args) {
        // Simulate fetching book data from a database
        return { title: args.title, author: 'Unknown Author' };
      },
    },
  },
});

const schema = new GraphQLSchema({
  query: RootQuery,
});

app.use('/graphql', graphqlHTTP({ schema, graphiql: true }));

app.listen(4000, () => {
  console.log('Server is running on port 4000');
});
```

### Step 3: Run your server using ts-node

```bash
npx ts-node index.ts
```

### Step 4: Open your browser and navigate

To access the GraphQL playground, open your browser and visit [<mark>http://localhost:4000/graphql</mark>](http://localhost:4000/graphql)<mark>.</mark> You may run interactive searches here.

### Step 5: Test query to retrieve a book by its title

```graphql
query {
  book(title: "The Hitchhiker's Guide to the Galaxy") {
    title
    author
  }
}
```

### How Does TypeScript Empower Type-Safe Development?

[TypeScript](https://en.wikipedia.org/wiki/TypeScript), a statically typed JavaScript, enables compile-time error detection and [GraphQL](https://www.apollographql.com/blog/graphql/basics/what-is-graphql-introduction/)\-based type safety. It allows for consistent data structures on both servers and clients, integrating back-end schema types into front-end codebases, providing auto-completion, tooling support, and reducing runtime errors.

### Why Use GraphQL and TypeScript Together?

The combination of [GraphQL](https://en.wikipedia.org/wiki/GraphQL) with [TypeScript](https://www.npmjs.com/package/typescript) provides a development experience that combines flexibility and dependability. It provides several benefits, including compile-time validation, automatic documentation, strong refactoring, and increased communication between server and client teams. Furthermore, [TypeScript](https://github.com/microsoft/TypeScript)'s strong typing boosts [GraphQL](https://www.redhat.com/en/topics/api/what-is-graphql)'s functionality by guaranteeing that your data is consistent and errors are identified before they reach production.

## What are the steps involved in setting up a [GraphQL](https://graphql.com/) server using the [NestJS](https://github.com/nestjs/nest) framework and TypeScript?

The process of configuring a [GraphQL](https://graphql.org/) server with the [NestJS](https://kinsta.com/knowledgebase/nestjs/) framework, establishing a strongly typed schema, implementing resolvers, and exploiting [TypeScript](https://code.visualstudio.com/docs/languages/typescript)'s advantages to provide a more secure, efficient, and maintainable API.

### Step1:Nest CLI to create a new project

```bash
npx @nestjs/cli new common-project
```

### Step 2: Navigate to your project directory

```bash
cd common-project
```

### Step 3: Install the required dependencies for GraphQL and [TypeORM](https://orkhan.gitbook.io/typeorm/docs):

```bash
npm install @nestjs/graphql @nestjs/typeorm graphql typeorm
```

### Step 4: Create data models using TypeScript classes

```typescript
// src/user/user.entity.ts
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}
```

### Step 5: Configure your database connection in the app.module.ts.

```typescript
// src/app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user/user.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'data.db',
      entities: [User],
      synchronize: true,
    }),
  ],
})
export class AppModule {}
```

### Step 6: Define your GraphQL schema and resolvers

```typescript
// src/user/user.resolver.ts
import { Resolver, Query } from '@nestjs/graphql';
import { User } from './user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Resolver(() => User)
export class UserResolver {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  @Query(() => [User])
  async users(): Promise<User[]> {
    return this.userRepository.find();
  }
}
```

### Step 7: Set up the GraphQL module in app.module.ts

```typescript
// src/app.module.ts
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { UserResolver } from './user/user.resolver';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user/user.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'data.db',
      entities: [User],
      synchronize: true,
    }),
    GraphQLModule.forRoot({
      autoSchemaFile: true,
    }),
  ],
  providers: [UserResolver],
})
export class AppModule {}
```

### Step 8: Start your [NestJS](https://www.turing.com/blog/what-is-nest-js-why-use-it/) application using the [Nest](https://blog.bytescrum.com/microservices-in-nestjs) CLI

```bash
npm run start
```

### Step 9: Open your browser and navigate GraphQL playground

To access the [GraphQL](https://medium.com/devgorilla/what-is-graphql-f0902a959e4) playground, open your browser and go to [<mark>http://localhost:3000/graphql</mark>](http://localhost:3000/graphql)<mark>.</mark> You may now run GraphQL queries and investigate your schema.

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent">Using <a target="_blank" rel="noopener noreferrer nofollow" href="https://docs.nestjs.com/recipes/sql-typeorm" style="pointer-events: none">TypeORM </a>to integrate <a target="_blank" rel="noopener noreferrer nofollow" href="https://nestjs.com/" style="pointer-events: none">NestJS</a>, <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.techtarget.com/searchapparchitecture/definition/GraphQL" style="pointer-events: none">GraphQL</a>, and a SQL database results in a strong stack for designing efficient and maintainable APIs. The procedure begins with the creation of a <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.udemy.com/course/nestjs-the-complete-developers-guide/" style="pointer-events: none">NestJS</a> project, followed by the installation of dependencies, the definition of data models in <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.freecodecamp.org/news/learn-typescript-beginners-guide/" style="pointer-events: none">TypeScript</a>, and the configuration of the <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.tutorialspoint.com/typeorm/typeorm_quick_guide.htm" style="pointer-events: none">TypeORM</a> connection to the SQL database. You can easily obtain and alter data using a well-defined GraphQL schema and resolvers that connect with <a target="_blank" rel="noopener noreferrer nofollow" href="https://typeorm.io/" style="pointer-events: none">TypeORM</a> repositories. This integration provides robust typing across the application, quick querying with GraphQL, and the <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.freecodecamp.org/news/build-web-apis-with-nestjs-beginners-guide/" style="pointer-events: none">NestJS</a> framework's features. The GraphQL playground becomes a testing environment for your queries as you run the application, making it easy to create and enhance your API.</div></details>
