Recently completed a simple blogging system using Nextjs + TypeORM + TypeScript. Functions include: login registration, blog add, delete and change, automatic deployment, Docker container, Nginx gZIP configuration. Code address: github.com/Maricaya/ne… . The preview address is http://121.36.50.175/. Have to say SSR is really fragrant, almost no white screen time, loading very fast.

Last time we talked about how to start building a project with Nex.js + TS, let’s look at how to introduce TypeORM to our project.

Object Relational Mapping (ORM) is a programming technique used to translate data between different types of systems in object-oriented programming languages. In effect, it creates a “virtual object database” that can be used in a programming language.

– Wikipedia – Object relational mapping ORM

What is the ORM

For those of you who don’t know about the back end, let me explain it briefly.

When working with a database, we all know to use a lot of SQL statements like this:

SELECT * FROM users where WHERE email ='[email protected]';
Copy the code

When using the ORM library, our code looks like this:

var orm = require('one-orm-libarry');
var user = orm("users").where({ email: '[email protected]' });
Copy the code

The above two pieces of code execute the exact same query, but we can use the more familiar JS to manipulate the database.

ORM also helps us encapsulate some complex operations, making it easier to manipulate the database.

Therefore, for xiao Bai, it is necessary to add ORM to the project. (You can write your own high-performance SQL)

TypeORM profile

TypeORM is an ORM for converting JavaScript/TypeScript data to various databases. It supports migration between MySQL/MariaDB/Postgres/SQLite/Microsoft SQL Server/Oracle/SQl.js.

It is currently at version 0.2.25, and although v1.0.0 has not been officially released, it is very popular with the Node.js community.

It supports basic operations such as Associations, transactions, and Migration.

Most importantly, it supports TypeScript by default.

With TypeORM in mind, let’s write some code. First, create a database.

Creating a database

Create PostgreSQL in Docker

Finally, I chose to create a PostgreSQL database blog in a Docker container and expose port 5432 to the host. (I default that you already know simple Docker operations)

mkdir blog-data
docker run -v "$PWD/blog-data": / var/lib/postgresql/data - p, 5432:5432 - e - e POSTGRES_USER = blog POSTGRES_HOST_AUTH_METHOD = trust - d postgres: 12.2Copy the code

SQL to create

A mature ORM framework should give us an API for creating databases, but TypeORM does not have =.=

The formal development process requires the creation of three databases: Development, Test, and Production.

Let’s create the development database blog_development this time.

Docker exec –it container ID bash Enter pg, PSQL -u blog -w.

CREATE DATABASE blog_development ENCODING 'UTF8' LC_COLLATE 'en_US.utf8' LC_CTYPE 'en_US.utf8';
Copy the code

\lViewing the current database

Ok, no problem! Next, install TypeORM for our project.

Install TypeORM

Following the code from last time, first install the dependencies

yarn add typeorm reflect-metadata @types/node pg
Copy the code

Then modify tsconfig

"compilerOptions": {
    "emitDecoratorMetadata": true."experimentalDecorators": true,}Copy the code

We run NPX typeORm init –database postgres to initialize typeORm.

Note this command will be modified. Gitignore/package. Json/tsconfig. Json file, remember to restore, the specific we look at what needs to be modified.

This command also creates some files for us:

The SRC │ ├ ─ ─ the entity / / entity │ │ └ ─ ─ the User. The ts │ ├ ─ ─ but ts │ └ ─ ─ migration / / migrationCopy the code

We don’t look at the official example, delete user. ts, delete all related user. ts in index.ts. (You’ll create your own entity file later)

Finally, configure our database information in ormconfig.json:

"username": "blog"."password": ""."database": "blog_development".Copy the code

Important configuration: Sync is disabled

Important: Add configuration to ormconfig.json:"synchronize": false.

Sync means to synchronize. If true, typeorm checks whether the current Entity has a table in the database each time it connects to the database. If not, it automatically changes the table based on the Entity directory.

Assuming that the Entity has a User in it, the User table is automatically created, that is, the code is automatically synchronized with the database.

Why disable

Inexperienced students may have such a question, looks very convenient ah, why to disable?

Because sync might delete data while modifying the User.

For example, if we change the name of User to nickName, TypeORM thinks that you deleted the name and added the nickName. Then it will delete all names and create an empty column nickName.

This behavior should never happen in a production environment, so we disabled sync from the start.

How do I run TypeScript

In the TypeScript community, there are two ways to run TypeScript. One is to use Babel to compile TS to JS, and the other is to use TS-Node to run directly.

The support for TS in these two modes is not completely consistent, and there are many incompatibilities if used together.

TypeORM recommends using TS-Node for compilation, but the other framework I use, Next. Js, uses Babel built-in to run TS.

So we had to unify it all with Babel.

steps

1. Install the Babel

Upgrade Node.js to V14 and then install @babel/cli yarn add @babel/ CLI

The files in SRC are then compiled into JavaScript using Babel.

npx babel ./src --out-dir dist --extensions ".ts,.tsx"
Copy the code

But it didn’t work. I reported a bunch of errors.

2. Install the plugin – proposal – decorators

Let’s look at the error and search for the answer:

Support for the experimental syntax ‘decorators-legacy’ isn’t currently enabled

This post and our error is the same, the highest praise answer said

I had the same problem,

but I was able to get it working by running npm install --save-dev @babel/plugin-proposal-decorators and adding ["@babel/plugin-proposal-decorators", { "legacy": true }] to the plugins section in my .babelrc.

Let’s go ahead and install the plugin:

yarn add --dev @babel/plugin-proposal-decorators
Copy the code

If you go to the official website of Next. Js and check the default configuration of.babelrc, it is found that custom.babelrc is supported.

To create.babelrc, add the default configuration for next-js.

{
  "presets": ["next/babel"]."plugins": []}Copy the code

Then add the plugin [“@babel/plugin-proposal-decorators”, {” Legacy “: true}].

Rerun the failed command and it succeeds.

Translated document:

Dist │ ├── entity │ ├── User.js │ ├─ index.jsCopy the code

If you run node dist/index.js directly, you will still get an error.

3. Modify ormconfig. Json

Since ormconfig.json is still configured by default, running node dist/index.js will still look for entity, migrations, and subscribers under SRC.

Modify ormconfig:

"entities": [
  "dist/entity/**/*.js"]."migrations": [
  "dist/migration/**/*.js"]."subscribers": [
  "dist/subscriber/**/*.js"
]
Copy the code

Run node dist/index.js again and it works!

Workflow summary

Let’s see what we’ve done so far:

  • Let next-js and TypeORM use Babel to translate TS
  • TypeORM
    • Each time the TS code of SRC is modified, it needs to be translated into a JS file and stored in the dist directory
    • Execute the TypeORM task by running JS in dist using Node
  • Next.js
    • After modifying the TS file in the pages directory, Next. Js will translate the TS file into js file when browsing the request and put it in the.next folder
      • Run JS in dist using Node

Having covered how to introduce TypeORM into your project and some basic configurations, the next article takes a look at how to use TypeORM to manipulate databases.