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

First, the development process of the project

  • Determine the requirements
  • Initialize the project
  • Front end development
  • The deployment of

Determine the requirements

The original intention of doing blog system is to create a small space where everyone can post blog and comment

Based on the above concept, the product requirement is created

Initialize the project

If you’re smart, you can look at the title of the article and figure out, what technology is used in the project

Js + Typeorm+ TS

TS is already familiar, but what about next.js and Typeorm

Let me introduce you

Next.js

Next. Js is positioned as the Node.js full stack framework, which has many advantages

  • Page pre-rendered SSR SSG
  • Isomorphism before and after
  • Support the React
  • Support the Typescript

disadvantages

  • No data manipulation at all. Workaround: Use Typeorm or Sequelize
  • No test related functionality at all. Solution: With Jest and Cypress

To get a better idea of how tO render Next js, take a look at my blog post on the three rendering methods of next.js (BSR, SSG, SSR)

Typeorm

Typeorm We can understand Type + ORm

Type can be understood as Typescript, and supporting Typescript is why I chose this framework

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

As you can see from this example, the ORM writing method is significantly more convenient and concise

SELECT id, first_name, last_name, phone, birth_date, P = person.get (10); p = person.get (10); name = p.first_name;Copy the code

So let’s get started

Use scaffolding to create projects

NPM init next-app nextjs-blog // next-js-blog is the project nameCopy the code

Select the Default Starter app

Go to next-js-blog and run YARN Dev

When you see this page, it’s a success

Start the Typescript

yarn add --dev typescript @types/react @types/node
yarn dev
Copy the code

Then we change the file name index.js to index.tsx

The index. The TSX instead

import React from "react" import {NextPage} from 'next'; Const Index: NextPage = () => {return (<div> home </div>)} export default Index;Copy the code

Tsconfig strengthen

Add it to tsconfig.json

“noImplicitAny”: true

Disable implicit any if you want to learn TS

Link Quick navigation

Please refer to the official website for details

We usually use the A tag to jump to the page, and Next recommends that we use the tag. Is there some black magic? Let’s find out

First, use a tag and Link tag respectively in the project to realize the mutual jump between the home page and the first article

pages/index.tsx

import React from "react" import {NextPage} from 'next'; const Index: NextPage = () => {return (<div> <a href="/posts/first-post"><a > Link href="/posts/first-post"><a > Link </a></Link> </div>)} export default Index;Copy the code

pages/posts/first-post.tsx

Import React from "React" import {NextPage} from 'next'; const FirstPost: NextPage = () => { return ( <div>First Post</div> ) } export default FirstPost;Copy the code

The experiment began

First, we jump between the two pages using the A tag. From the console, we can see that the browser has requested THE HTML CSS JS again

Next, we use Link to repeat the above operation, and the amazing thing is that the browser only sends two requests

The second request is webpack, so only one request is actually sent, which is first-post.js

Let’s take a look at the dark magic

The traditional navigation

When the user clicks on the A tag, it requests the HTML, parses the HTML, and requests the CSS and JS referenced in the HTML

Link Fast Navigation

For the first load, the browser requests HTML, CSS, and JS in turn, just like traditional navigation

When the user clicks Link, parse the Link tag and request page2.js via AJAX, and page2.js is actually the HTML + CSS + JS of Page2

After requesting page2.js, the browser does not need to access page2. Instead, it converts the contents of page1 into page2 via page2.js

advantages

  • Instead of refreshing the page, AJAX requests new page content
  • Do not request duplicate HTML, CSS, JS
  • Automatically inserts new content and deletes old content on the page
  • It is extremely fast because it saves a lot of requests and parsing

Isomorphic code

As the SSR rendering method used in our project, that is, server-side rendering, isomorphic code is written

Homogeneous code is code that runs on both the client and server sides

For example, we write console.log(‘ executed ‘) in the component.

You’ll notice that the Node console will output this sentence, as will the Chrome console

Pay attention to the differences between

  • Not all code will run, and some will need to be triggered by the user
  • Not all apis work; for example, Windows do not exist in Node

Next.js API

So far we’ve been writing HTML pages

In fact, we need to request /user /shops apis that return JSON strings

Let’s start with a simple API

Using the Next. Js API

We used the path/API /v1/posts to distinguish it from /posts

The default export function is of type NextApiHandle

This code only runs in Node.js, not in the browser

/pages/api/v1/posts.tsx

import {NextApiHandler} from 'next';

const Posts:NextApiHandler = (req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.write(JSON.stringify({name: 'Jacky'}));
  res.end();
};

export default Posts;
Copy the code

Access localhost: 3000 / API/v1 / posts

This means that the API is accessible (the effect in the picture is because I installed the Chrome plugin JSON Viewer).

Transform posts

The Posts API currently doesn’t return a list of blogs, so let’s change that

Since we haven’t created the database yet, let’s create a Markdown directory in the root directory and write a few md blogs

We then use gray-matter to parse the data from the MD file

The lib/posts.tsx file exports JSON data

import path from "path";
import fs, {promises as fsPromise} from "fs";
import matter from "gray-matter";

export const getPosts = async () => {
  const fileNames = await fsPromise.readdir(find('markdown'))
  return fileNames.map(fileName => {
    const id = fileName.replace(/\.md$/, '')
    const fullPath = find('markdown', fileName)
    const content = fs.readFileSync(fullPath, 'utf-8')
    const {title, date} = matter(content).data
    return {
      id, title, date
    }
  })
}
Copy the code

Now that you’ve read the data, it’s time to refine the Posts API. When a request is received, the Posts API takes the data from lib/posts.tsx and returns it to the front end

import {NextApiHandler} from 'next';
import {getPosts} from 'lib/posts';


const Posts: NextApiHandler = async (req, res) => {
  const posts = await getPosts();
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.write(JSON.stringify(posts));
  res.end();
};
export default Posts;
Copy the code

At this point, again access localhost: 3000 / API/v1 / posts page, you can get markdown articles in the catalog

To be continued…

Next. Js + Typerom Practice – Blog System (middle)

If you are interested in the three rendering modes of next.js, please check out the three rendering modes of next.js (BSR, SSG, SSR).