Sling Academy
Home/Node.js/NestJS & SQLite: A Basic CRUD Example

NestJS & SQLite: A Basic CRUD Example

Last updated: January 01, 2024

Overview

NestJS combined with SQLite provides a powerful yet simple solution for creating robust, scalable server-side applications (you can use SQLite right away without any setup and configuration). This tutorial will walk you through a basic CRUD example using these technologies.

Setting Up the Environment

Before we begin, make sure you have Node.js installed. Then, install NestJS CLI globally on your machine using the following npm command:

npm i -g @nestjs/cli

Now, create a new NestJS project:

nest new project-name

Change directory into your new project:

cd project-name

Next, let’s install the required SQLite package:

npm install sqlite3@latest @nestjs/typeorm typeorm

Configuring the Database Module

After installing the dependencies, set up TypeORM with SQLite within your NestJS project. You will start by importing the TypeORM module into app.module.ts.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

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

Creating the Entity

Now, create a new entity that represents the table structure in your SQLite database.

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

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

  @Column()
  name: string;

  @Column()
  description: string;
}

Then, add this entity to your app.module.ts:

import { Item } from './item.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      ... // other options remain the same
      entities: [Item],
    }),
  ],
})

Creating a Service

To handle the business logic, create a service using NestJS CLI:

nest generate service items

In your items.service.ts, inject the repository and define CRUD operations.

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Item } from './item.entity';

@Injectable()
export class ItemsService {
  constructor(
    @InjectRepository(Item)
    private readonly itemRepository: Repository<Item>,
  ) {}

  // Add methods for CRUD operations here
}

Defining the Controller

Create a controller to handle the incoming requests:

nest generate controller items

Add the CRUD operations in your items.controller.ts by using the service methods:

import { Controller, Get, Post, Body, Put, Param, Delete } from '@nestjs/common';
import { ItemsService } from './items.service';
import { Item } from './item.entity';

@Controller('items')
export class ItemsController {
  constructor(private readonly itemsService: ItemsService) {}

  // Add routes for CRUD operations here
}

Implementing CRUD Operations

Add the actual CRUD methods in the service and use them in the controller. For example, to create an item:

@Post()
async create(@Body() itemData: Item): Promise<Item> {
  return this.itemsService.create(itemData);
}

The corresponding service method might look like this:

async create(itemData: Item): Promise<Item> {
  const newItem = this.itemRepository.create(itemData);
  await this.itemRepository.save(newItem);
  return newItem;
}

Add similar methods for reading, updating, and deleting items.

You can now test your CRUD operations using a REST client, such as Postman, or by using curl commands in your terminal.

Conclusion

In this tutorial, you have learned how to build a basic CRUD application using NestJS and SQLite. With these foundational skills, you’re now equipped to expand upon and customize your application to suit your specific needs.

Next Article: How to Deploy a NestJS Application to Heroku

Previous Article: NestJS & PostgreSQL: A Simple CRUD Example

Series: Nest.js Tutorials: From Basics to Advanced

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates