2k1
  • Home
  • Programming
  • System
  • Design
  • Applications
  • Tech
No Result
View All Result
  • Login
2k1
  • Home
  • Programming
  • System
  • Design
  • Applications
  • Tech
No Result
View All Result
2k1
No Result
View All Result

NestJs với prisma restapi

Nguyen Pham by Nguyen Pham
13/02/2022
in Programming
Reading Time: 5 mins read
A A
0

Tạo một ứng dụng nest mới

Cài đặt Nodejs

Kiểm tra phiên bản nodejs hiện tại

λ node -v
v16.13.0

Nếu mấy chưa cài NodeJs thì có thể vào trang chủ nodejs và download về. Nên chọn bản LTS để ổn định hơn

Cài đặt NestJs/CLI

Cài đặt nestjs/cli bằng npm

npm install -g @nestjs/cli

Tạo một nest application mới

cú pháp nest new tên_project

Lưu ý:

Khi nó hiện câu hỏi Which package manager would you ❤️ to use?

thì hãy chọn npm

Với yarm mình chưa thử nhưng pnpm thì khi dùng với prisma sẽ lỗi nên cứ chọn npm

nest new nest-prisma-tutorial

Cài đặt prisma

Cài đặt prisma package

npm install prisma --save-dev

Khởi tạo prisma

npx prisma init

Cấu hình database

schema.prisma

File này sẽ chứa các model

datasource

Cái này để kết nối với csdl

provider Loại cơ sở dữ liệu muốn kết nối

url Đường dẫn csdl (Lấy từ file env)

env

DATABASE_URL="file:./db.sqlite"
// This is your Prisma schema file,
// learn more about it in the docs: <https://pris.ly/d/prisma-schema>

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

Như vậy chúng ta đã hoàn thành kết nối prisma với csdl

Viết model

Chúng ta sẽ định nghĩa model ở trong file schema.prisma

Đây là model có tên là Task

gồm thuộc tính:

  • id: tự động tăng
  • title: chuỗi
  • comleted: boolean
model Task {
  id        Int @id @default(autoincrement())
  title     String
  completed Boolean
}

Tạo nest module mới

Tạo module task

Module này sẽ tự import vào app.module.ts

nest g module task

Tạo controller task

controller sẽ được import vào task.module.ts

⇒ Xử lý các request từ người dùng

nest g comtroller task

Tạo service task

service sẽ được import vào task.module.ts

⇒ Viết các thao tác xử lý với cơ sở dữ liệu

nest g service task

Viết task service

import { Injectable, ParseIntPipe } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
@Injectable()
export class TaskService {
  create(title, completed) {
    prisma.task.create({
      data: {
        title: title,
        completed: completed ? true:false,
      },
    }).then(res=>{
      return res
    });
    // return 'create services';
  }
  get() {
    const dt = prisma.task.findMany({
      select:{
        title: true,
        completed: true
      }
    })
    return dt
  }
  getOne(id){
    const dt = prisma.task.findFirst({
      where:{
        id: id
      }
    })
    return dt
  }
}

Viết task controller

Khởi tạo service

constructor(private readonly taskService: TaskService) {}

Sau khi khởi tạo ta có thể dùng các hàm trong service để xử lý

import { Body, Controller, Get, Param, ParseIntPipe, Post } from '@nestjs/common';
import { TaskService } from './task.service';

@Controller('task')
export class TaskController {
  constructor(private readonly taskService: TaskService) {}

  @Get()
  getTask() {
    return this.taskService.get();
  }
  @Get('/:id')
  getOne(@Param('id', ParseIntPipe) id:number) {
    return this.taskService.getOne(id);
  }

  @Post()
  createTask(@Body() body) {
    const { title, completed } = body;
    this.taskService.create(title, body);
    return 'Task is created';
  }
}

Chạy và test thử

Chạy ta dùng lệnh

npm run start:dev
Tags: apinestjsprismarest-api
Previous Post

Cài đặt Windows Subsystem for Android windows 11

Next Post

Tạo một node n8n mới

Related Posts

Xây dựng todo app với smartcontract
Go

Giới thiệu về đa luồng trong ngôn ngữ lập trình go có code minh họa.

by Nguyen Pham
29/06/2023
Programming

Lập trình rust cơ bản – vòng lặp

by Nguyen Pham
22/12/2022
Programming

Lập trình python cơ bản – Hello world

by Nguyen Pham
16/11/2022
Programming

Lập trình go cơ bản – Hello world

by Nguyen Pham
04/12/2022
Programming

Lập trình rust cơ bản – Biến

by Nguyen Pham
16/11/2022
Programming

Lập trình rust cơ bản – hello world

by Nguyen Pham
14/11/2022
Load More
Next Post

Tạo một node n8n mới

Please login to join discussion
Stock

Phân tích mã cổ phiếu VCB

by Nguyen Pham
26/04/2025
0

Phân tích mã cổ phiếu VCB (Ngân hàng TMCP Ngoại thương Việt Nam - Vietcombank) 1. Tổng quan về Vietcombank...

Read more

Facebook, Instagram bất ngờ sập trên diện rộng, liên tục đăng xuất người dùng!

05/03/2024
Xây dựng todo app với smartcontract

Web3 là gì?

30/06/2023
Xây dựng todo app với smartcontract

Giới thiệu về đa luồng trong ngôn ngữ lập trình go có code minh họa.

29/06/2023

Chạy ứng dụng react native đầu tiên của bạn

29/06/2023

@2021 2k1.org [email protected]

No Result
View All Result
  • Home
  • Review
  • Applications
  • Computers
  • Gaming
  • Microsoft

© 2021 NData

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In