Using TypeORM to interact with SQLite databases is a relatively straightforward process. Below are some basic steps and examples to guide you through the process.
Step 1: Install TypeORM and SQLite3
First, install TypeORM and SQLite3 in your Node.js project. If you haven't initialized a project yet, use npm init to create a new one. Then run the following commands:
bashnpm install typeorm sqlite3 reflect-metadata
reflect-metadata is a dependency required by TypeORM for decorators.
Step 2: Configure TypeORM
Create a configuration file named ormconfig.json in the root directory of your project, specifying the following SQLite database configuration:
json{ "type": "sqlite", "database": "database.sqlite", "entities": ["src/entity/**/*.ts"], "synchronize": true, "logging": false }
The "entities" path should point to the directory containing your entity classes.
Step 3: Define Entities
Defining entity classes models the tables in the database. Create an entity class file User.ts as an example:
typescriptimport { Entity, PrimaryGeneratedColumn, Column } from "typeorm"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() firstName: string; @Column() lastName: string; @Column() age: number; }
Step 4: Connect to the Database and Perform Operations
Next, create a script to establish a database connection and perform CRUD operations. In your index.ts (or other entry point file), use the following code to connect to the database and execute operations:
typescriptimport "reflect-metadata"; import { createConnection } from "typeorm"; import { User } from "./entity/User"; createConnection().then(async connection => { console.log("Inserting a new user into the database..."); const user = new User(); user.firstName = "Timber"; user.lastName = "Saw"; user.age = 25; await connection.manager.save(user); console.log("Saved a new user with id: " + user.id); console.log("Loading users from the database..."); const users = await connection.manager.find(User); console.log("Loaded users: ", users); console.log("Here you can setup and run express/koa/any other framework."); }).catch(error => console.log(error));
In this code, we first establish a connection, insert a new user, query all users, and print the results.
Step 5: Run the Project
After completing the above steps, run your Node.js application. If your entry file is index.ts, execute it with the following command:
bashnpx ts-node src/index.ts
Ensure you have installed ts-node to run TypeScript files.
Summary
This outlines the basic steps for working with TypeORM and SQLite databases. TypeORM is a powerful ORM that simplifies interaction with SQLite (and many other databases) and provides rich decorators and methods for managing your data models and database operations.