Git Product home page Git Product logo

nestgraphql's Introduction

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications, heavily inspired by Angular.

NPM Version Package License NPM Downloads Travis Linux Coverage Gitter Backers on Open Collective Sponsors on Open Collective

Description

Nest framework TypeScript starter repository.

Installation

$ git clone https://github.com/Bouabidi/nestgraphql.git
$ cd nestgraphql
$ npm install

Running the app

# start Mongodb
# open a terminal and run the server
$ npm run start:dev

Test

# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov

Tutorial

  1. nest new nestgraphql

  2. cd nestgraphql

  3. npm i --save @nestjs/graphql apollo-server-express graphql-tools graphql @nestjs/mongoose mongoose type-graphql

  4. nest g module items

  5. nest g service items

  6. nest g resolver items

in items folder add the following:

  1. add createitem.dto.ts
  2. add item.interface.ts
  3. add inputitems.input.ts
  4. add item.schema.ts
  5. add item.graphql

update AppModule and import GraphQLModule

import { GraphQLModule } from '@nestjs/graphql';
@Module({
 imports: [
  GraphQLModule.forRoot({
   autoSchemaFile: 'schema.gql',
  })]
export class AppModule {}

add the connection to the database by importing MongooseModule

import { MongooseModule } from '@nestjs/mongoose';

@Module({
 imports: [
  MongooseModule.forRoot('mongodb://localhost/nestgraphql')
 ],
})
export class AppModule {}

update item.schema.ts

import * as mongoose from 'mongoose';

export const ItemSchema = new mongoose.Schema({
 title: String,
 price: Number,
 description: String,
});

update item.interface.ts

import { Document } from 'mongoose';

export interface Item extends Document {
 readonly title: string;
 readonly price: number;
 readonly description: string;
}

update createitem.dto.ts

import { ObjectType, Field, Int, ID } from 'type-graphql';

@ObjectType()
export class ItemType {
  @Field(() => ID)
  readonly id?: string;
  @Field()
  readonly title: string;
  @Field(() => Int)
  readonly price: number;
  @Field()
  readonly description: string;
}

update inputitems.input.ts

import { InputType, Field, Int } from 'type-graphql';

@InputType()
export class ItemInput {
  @Field()
  readonly title: string;
  @Field(() => Int)
  readonly price: number;
  @Field()
  readonly description: string;
}

create database:

import our schema into ItemsModule

@Module({
 imports: [MongooseModule.forFeature([{ name: 'Item', schema: ItemSchema }])],
providers: [ItemsResolver, ItemsService],
})
export class ItemsModule {}

implement crud with GraphQL

--first create crud functionality there for we will update our service we will import the database model and implement functionality using Mongodb functions.

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ItemType } from './dto/create-item.dto';
import { Item } from './interfaces/item.interface';
import { ItemInput } from './input-items.input';

@Injectable()
export class ItemsService {
  constructor(@InjectModel('Item') private itemModel: Model<Item>) {}

  async create(createItemDto: ItemInput): Promise<ItemType> {
    const createdItem = new this.itemModel(createItemDto);
    return await createdItem.save();
  }

  async findAll(): Promise<ItemType[]> {
    return await this.itemModel.find().exec();
  }

  async findOne(id: string): Promise<ItemType> {
    return await this.itemModel.findOne({ _id: id });
  }

  async delete(id: string): Promise<ItemType> {
    return await this.itemModel.findByIdAndRemove(id);
  }

  async update(id: string, item: Item): Promise<ItemType> {
    return await this.itemModel.findByIdAndUpdate(id, item, { new: true });
  }
}

---resolver now we can implement our Resolver. Resolver can be seen as a controller in a crud functionality without GraphQL. Querys and Mutations will be defined.

import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { ItemsService } from './items.service';
import { ItemType } from './dto/create-item.dto';
import { ItemInput } from './input-items.input';

@Resolver()
export class ItemsResolver {
  constructor(private readonly itemsService: ItemsService) {}

  @Query(() => [ItemType])
  async items(): Promise<ItemType[]> {
    return this.itemsService.findAll();
  }

  @Mutation(() => ItemType)
  async createItem(@Args('input') input: ItemInput): Promise<ItemInput> {
    return this.itemsService.create(input);
  }

  @Mutation(() => ItemType)
  async updateItem(
    @Args('id') id: string,
    @Args('input') input: ItemInput,
  ): Promise<ItemInput> {
    return this.itemsService.update(id, input);
  }

  @Mutation(() => ItemType)
  async deleteItem(@Args('id') id: string): Promise<ItemInput> {
    return this.itemsService.delete(id);
  }

  @Query(() => String)
  async hello() {
    return 'hello';
  }
}

---item.graphql update the file

input ItemInput {
  title: String!
  price: Int!
  description: String!
}

type ItemType {
  id: ID!
  title: String!
  price: Int!
  description: String!
}

type Mutation {
  createItem(input: ItemInput!): ItemType!
  updateItem(input: ItemInput!, id: String!): ItemType!
  deleteItem(id: String!): ItemType!
}

type Query {
  items: [ItemType!]!
  hello: String!
}

nestgraphql's People

Contributors

bouabidi avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.