Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Creating a Complete CRUD API Part One | Section
Building Backend Applications with Nest.js

bookCreating a Complete CRUD API Part One

Stryg for at vise menuen

Now you will combine several Nest.js concepts and start building a small CRUD API.

CRUD stands for:

  • Create;
  • Read;
  • Update;
  • Delete.

In this part, you will set up a simple users API with routes for creating users and getting all users.

Start with the service:

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  private users = [
    { id: 1, name: 'Alice', age: 30 },
    { id: 2, name: 'Bob', age: 25 },
  ];

  getAllUsers() {
    return this.users;
  }

  createUser(user: { name: string; age: number }) {
    const newUser = {
      id: this.users.length + 1,
      ...user,
    };

    this.users.push(newUser);
    return newUser;
  }
}

Here is what is happening:

  • users: stores the current list of users;
  • getAllUsers(): returns all users;
  • createUser(): creates a new user and adds it to the array.

Now update the controller:

import { Controller, Get, Post, Body } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Get()
  getUsers() {
    return this.usersService.getAllUsers();
  }

  @Post()
  createUser(@Body() body: { name: string; age: number }) {
    return this.usersService.createUser(body);
  }
}

Here is what is happening:

  • @Get(): returns all users;
  • @Post(): creates a new user;
  • @Body(): gets data from the request body;
  • The controller passes the work to the service.

With this setup, your API can already:

  • Return all users;
  • Create a new user.

This is the first half of a CRUD API.

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 21

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 1. Kapitel 21
some-alt