Next. Js Scaffolding advanced series

  • Perfect for Ant-Design
  • Package fetch && add middleware
  • The deployment of online
  • Zeit Now deployed
  • Extended for full stack scaffolding

Writing in the front

As a front-end, or front-end in a general sense, it should only do what the front-end should do, and there may be little knowledge about the back-end. Even, when we use the server rendering framework, we just regard it as a means to optimize the first screen rendering speed and benefit SEO. This article extends the Next server rendering scaffold into a full stack scaffold by reverse thinking.

The branch is the Next-ANTD-Scaffold_Backend branch

In the past, when I did not touch the server side rendering, I always had this idea. Generally, NODEJS writing projects are generally nodeJS framework (EXPRESS) + database (MongoDB) + front-end rendering template. In ancient times, EJS, Jade and other rendering templates were used. As more front-end frameworks are written, popular front-end frameworks like React and Vue will be tried. Express + React + MongoDB (Express + React + MongoDB) I wrote an Express + React + MongoDB (Express + React + MongoDB)

Then slowly with the deepening of knowledge, reverse thinking, nodeJS write pseudo-full stack is actually a few elements, nodeJS + database + front-end page. In fact, server-side rendering frameworks already have some of the ingredients for writing big front-end projects. We only need to connect the routing API on the Node side, and then connect the database on the Node side, a simple full-stack architecture is completed. In fact, the rest is to carry out business development according to our previous writing habits and specifications. Of course, since it is full-stack, you need to design the database on the basis of writing only the front-end page in the past. Writing apis and more. Here I according to their own understanding of the rough draw a picture, mainly in order to let you can more simple understand my meaning ~

Article write more and more advanced 😄, began to do their own chart. Sometimes I think writing an article is really a good way to consolidate knowledge and sort out knowledge. I recommend you to try it, even if you don’t write an article, you can also write notes.

Let me explain why I call it a pseudo-full stack. Full stack, as the name implies, you do all the work by yourself, front-end page + back-end API + database design. But you’re only using Node routing and some middleware features, nodeJS doesn’t use a lot of advanced functionality and a lot of complex logic related to the background and database (things, locks, etc.). As a pseudo-full stack, I don’t really understand this, so this is not the place to explore complex logic, but to give you a simple idea.

Extension process

In fact, the overall extension process is really very simple, because we are directly through the SSR framework for extension, so there is no need to consider the page rendering part, that is, only need to consider the Node + database. Let’s review the overall directory structure of the project:

-- -- - | - assets / / ant - design global less var | - components / / React UI component | - constants / / constant directory | -- ActionsTypes.js // save all actiontype
      | -- ApiUrlForBE.js    // save all apiUrl
      | -- ...
  | -- containers            // React container component
  | -- core                  // mehtod dirctory
      | -- util.js           // project method
      | -- nextFetch.js      // packing unfetch foreasy use | -- middlewares // middlewares | -- client // client middlewares, deal redux action | -- server // server middlewares, deal node event | -- pages // Next.js routes | -- redux | -- actions // deal all projectaction | -- reducers // deal all  project reducer | -- sagas // sace all project saga | -- store.js | -- static // save staticsourcedirectory | -- .babelrc | -- .eslintrc | -- .gitignore | -- next.config.js // Next.js config file | -- package.json | --  server.js // server file | -- pm2.config.js // pm2 deploy config file | ... // other filesCopy the code

Above is the overall scaffolding front-end part of the architecture, we will next step to expand ~

Adding a Routing API

First, we create a /backend/routes folder to store the routing files on the front and back ends:

| -- backend               // node backend
      | -- routes            // the backend routes
Copy the code

Then, as a convention, the apis for the front and back end interaction are all in the form of http://${host}:${port}/api/${apiName}, and we register the API service in server.js, which is to add the routing middleware.

// server.js
const router = require('./backend/routes'); . // Routing middleware server.use('/api', router); // Add router middlewareCopy the code

Register successfully let’s try to write a front-end call node end interface, take the user list as an example:

// apiUrlForBE.js
const apiServer = `${process.env.API_HOST}:${process.env.PORT}/api`;
// const API url
exportDefault {/** * GET user list data * @method GET */ getUserList: '${apiServer}/user/list`
};
Copy the code

In the development environment, for example, we set up above apiServer = http://localhost:3006/api, which is all the front end of the request will go to our/API routing and then return the data.

// /backend/routes/user.js
const userData = [
  {
    "id": 1,
    "name": "Leanne Graham"."username": "Bret"."email": "[email protected]"."address": {
      "street": "Kulas Light"."suite": "Apt. 556"."city": "Gwenborough"."zipcode": "92998-3874"."geo": {
        "lat": "37.3159"."lng": "81.1496"}},"phone": "1-770-736-8031 x56442"."website": "hildegard.org"."company": {
      "name": "Romaguera-Crona"."catchPhrase": "Multi-layered client-server neural-net"."bs": "harness real-time e-markets"}}... ] Router.get ('/list', (req, res) => {
  const resData = {
    data: userData
  };
  res.json(resData);
});
Copy the code

Let’s start the service and have a look:

/api

Connecting to a Database

The above interface worked, but the interface we responded to was mock data, which is static, not retrieved from the database and returned to the front end, so we could take it one step further by connecting to the database.

We create a /db folder under the/Backend folder to link to our database and database configuration operations. The following uses mongoDB as an example to perform related configurations:

| -- backend               // node backend
    | -- db                // the directory of db
        | -- config        // db config directory
        | -- models        // mongoDB models
        | -- shcemas       // mongoDB schemas
    | -- routes            // the backend routes
Copy the code
// config/config.js'mongodb:// username: password @IP: port number/database '; Module. exports = {mongodb: // set user name and password to IP address.'mongo: / / 127.0.0.1:27017 / db - name'}; // /config/mogoose.js // create mogoose instance, link database const mongoose = require('mongoose');
const config = require('./config');

module.exports = () => {
  mongoose.connect(config.mongodb, { useNewUrlParser: true}); // Connect to mongodb database // instantiate connection object var db = mongoose. Connection; db.on('error', console.error.bind(console, 'Connection error:'));
  db.once('open', () => {
    console.log('MongoDB connection successful!! ');
  });
  return db;
};
Copy the code

Above we put the database expansion, the rest of the link is to connect to the database, add, delete, change, check operation and so on. If you are interested in exploring it, leave a comment if you want more details. The reason for not putting this code in the repository is that it would be less like scaffolding and more like a Demo.

With APIDOC to achieve automated interface documentation

After the above content is completed, we can start the journey of the full stack project. As an extra gift of the big package, since it is the full stack, there must be a huge API interface to write, which will be troublesome to maintain after a long time. In the past, all these works were done by the back end, but now the whole stack needs to be done by one person. Therefore, we will introduce an automatic API document generation tool — APIDOC, which can write simple annotations when we write code, and finally help us generate visual API interface documents. The final implementation looks like this:

For more detailed instructions, see my learn by Writing series 1 – Using APidOC to automate documents

conclusion

I like Next. Js very much, so I will write more articles in this series. Although few people use it, it is still good as a record. I welcome both issue and star. Communication and common progress are the most important.

[Note] : Here is just a primer, any SSR framework can actually be used in accordance with this routine when the full stack scaffolding, it will save a lot of time than we build from scratch, and the use of their most familiar front-end framework to do the template will certainly improve efficiency ~

Next. Js full stack scaffolding

Friends cannot be found in the Backend branch.