Recently, I completed the first full stack project of front-end Xiaobai with Next. Js and Typeorm. This article will record some knowledge points I learned in the process of doing the project, and those strange and strange bugs I encountered
Github – Submit the source address
Blog system – submit preview address and leave a blog post if you like
The previous article – documented the process of initializing the project, so this article initializes the database
Initializing the database
What is the ORM
ORM is the abbreviation of Object-Relational Mapping. The function of this technology is to complete the operation of relational databases through the syntax of instance objects. It can be seen from this example that the WRITING method of ORM is obviously more convenient and concise
SELECT id, first_name, last_name, phone, birth_date, sex
FROM persons
WHERE id = 10------ p = person.get (10);
name = p.first_name;
Copy the code
TypeORM
Typeorm is a library that uses JavaScript and Typescript to manipulate databases. It is currently in version 0.2.30 and has not been released yet. I intended to use Sequelize.js, but found that it does not support TS, so I chose this library instead. It has the following characteristics
- TypeSciprt is supported by default
- Support associated Associations
- Support transaction
- Database Migration is supported
A brief introduction to the old said, start typing code
Creating a database
Creating a database directory
- Create the blog-data directory in the project directory
.gitignore
– data/add/blog
Start the PostgreSQL
One command starts PG
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
If you get an error, check out this tutorial, or just Google it
If the download speed is slow, first search Ali cloud Docker image (to log in Ali cloud), and then search Docker acceleration
After startup
Docker logs container id docker logsCopy the code
SQL to create
A mature ORM framework typically provides an API for creating data, but Typeorm does not, so you have to do it manually ðŸ˜
Enter the Docker container
docker exec-it container ID bash // The container ID can be queried using docker ps -aCopy the code
Enter the pg
psql -U blog -W
Copy the code
Since the password is not required when starting PG, you can enter directly by pressing enter. If you need to add password, -e POSTGRES_HOST_AUTH_METHOD=trust can be replaced with -e POSTGRES_PASSWORD=123456 in docker run
Creating a database
According to the formal development process, we need to create three databases: development, test, and production
They are blog_development, blog_test, and blog_production
CREATE DATABASE blog_development ENCODING 'UTF8' LC_COLLATE 'en_US.utf8' LC_CTYPE 'en_US.utf8';
Copy the code
Some common pg commands
\l used for list databases, \c used for connecting to database, \dt used for displaying tables in databaseCopy the code
At this point, use the \l command and see that this is success ~
Install TypeORM
Install dependencies
yarn add typeorm reflect-metadata @types/node pg
Copy the code
Modify the tsconfig
"compilerOptions": {
"emitDecoratorMetadata": true."experimentalDecorators": true,}Copy the code
Run NPX TypeOrm init –database postgres to initialize the TypeOrm
This command will help us create some files including:
The SRC │ ├ ─ ─ the entity / / entity │ │ └ ─ ─ the User. The ts │ ├ ─ ─ but ts │ └ ─ ─ migration / / migrationCopy the code
Index. ts and user. ts are official examples. We can delete them first and create them later according to our own needs
Finally, configure our database information in ormconfig.json:
"username": "blog"."password": ""."database": "blog_development"
Copy the code
Disable sync — important configuration
Change “synchronize”: “ture” to “false” in ormconfig.json
If true, TypeOrM automatically modifies the data table based on the Entity directory when connecting to the database
Given that the entity has a User in it, the User table is automatically created
It looks so convenient, why disable it
Because sync may delete data directly when we modify the User
This kind of behavior can never happen in a production environment, so we need to eliminate Sync from the start
How do I run TypeScript
contradiction
Next. Js uses Babel by default to compile TS to JS (built-in feature)
TypeORM is recommended to compile using TS-Node (not built in)
Babel and TS-Node support for TS is not exactly the same
So we use Babel to compile TS
Install Babel
Upgrade Node.js to V14 and install @babel/cli yarn @babel/cli
The TS file in SRC is then compiled into JS using Babel
npx babel ./src --out-dir dist --extensions ".ts,.tsx"
Copy the code
Hit enter. Pop, quick
But it didn’t work out, and it made a bunch of mistakes
Experience has taught me not to panic when things go wrong
Pounce on mistakes
Support for the experimental syntax 'decorators-legacy' isn't currently enabled
After several hours of searching finally have the result 😥
I had the same problem
Then follow the operation
Installing a plug-in
yarn add --dev @babel/plugin-proposal-decorators
Copy the code
Next, modify the.babelrc file. We don’t have one, so create one
Now go to the next. Js website, look up the default configuration, and add the answer configuration
{
"presets": ["next/babel"]."plugins": [["@babel/plugin-proposal-decorators", { "legacy": true}}]]Copy the code
Rerun the command that just failed
Success!!
So where is the compiled JS code?
–out-dir dist –extensions “. Ts,.tsx” Look at the command to run –out-dir dist that’s dist of course
Dist /index.js (dist/index.js
Modify ormconfig. Json
Since ormconfig.json is still the default, I still run Entity, Migrations, and Subscribers files from SRC when I run Node dist/index.js
Modify ormconfig
"entities": [
"dist/entity/**/*.js"]."migrations": [
"dist/migration/**/*.js"]."subscribers": [
"dist/subscriber/**/*.js"
]
Copy the code
Run node dist/index.js again successfully!
Workflow summary
steps
- Unify Next. Js and TypeORM to translate TS using Babel
- After each modification of SRC TS code, translate it into JS in DIST
- Use Node to run JS in Dist and perform TypeORM tasks
This article documented the initialization process of the database, so let’s start working with the database using TypoORM in the next article