What?
let's create a basic CRUD operation in a NestJS application without using a database. Instead, we'll use an in-memory array to store the data. Here's a simple step-by-step guide:
Prerequisites:
- Node.js and npm installed.
- Basic knowledge of NestJS
Create a New NestJS Project:
If you haven't already, you can create a new NestJS project using the Nest CLI. Run the following command to generate a new NestJS application:
npm i -g @nestjs/cli
nest new nestjs-crud-no-db
cd nestjs-crud-no-db
Create the necessary modules, controllers, and services:
nest g module items
nest g controller items
nest g service items
Define the Item Model:
Create an item.interface.ts
inside the items folder:
export interface Item {
id: string;
name: string;
description: string;
}
Implement CRUD Operations in the Service:
Edit items.service.ts:
import { Injectable } from '@nestjs/common';
import { Item } from './item.interface';
@Injectable()
export class ItemsService {
private readonly items: Item[] = [];
findAll(): Item[] {
return this.items;
}
findOne(id: string): Item {
return this.items.find(item => item.id === id);
}
create(item: Item) {
this.items.push(item);
}
update(id: string, updatedItem: Item): void {
const index = this.items.findIndex(item => item.id === id);
if (index !== -1) {
this.items[index] = updatedItem;
}
}
delete(id: string): void {
const index = this.items.findIndex(item => item.id === id);
if (index !== -1) {
this.items.splice(index, 1);
}
}
}
Implement the Controller:
Edit items.controller.ts:
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
import { Item } from './item.interface';
import { ItemsService } from './items.service';
@Controller('items')
export class ItemsController {
constructor(private readonly itemsService: ItemsService) {}
@Get()
findAll(): Item[] {
return this.itemsService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string): Item {
return this.itemsService.findOne(id);
}
@Post()
create(@Body() item: Item): void {
this.itemsService.create(item);
}
@Put(':id')
update(@Param('id') id: string, @Body() updatedItem: Item): void {
this.itemsService.update(id, updatedItem);
}
@Delete(':id')
delete(@Param('id') id: string): void {
this.itemsService.delete(id);
}
}
Run your Application:
npm run start:dev
Now you can use tools like Postman or cURL to make requests to your NestJS application.
- GET /items: Fetch all items
- GET /items/{id}: Fetch an item by ID
- POST /items: Create a new item
- PUT /items/{id}: Update an existing item by ID
- DELETE /items/{id}: Delete an item by ID
This is a basic example and in a real-world application, you'd use proper database storage, handle edge cases, and include error handling.