TS&&Node: Project actual combat notes

TS&&Node: Project actual combat notes

1. Project initialization

  • First initialize an npm project

    npm init
    
  • Second, initialize the tsconfig.json file in the project directory

    tsc --init
    
  • Modify the tsconfig.json file, set the root directory and output directory:

    {
          
          
      "compilerOptions": {
          
          
        "target": "es5",  
        "module": "commonjs",            
        "outDir": "./dist",      // 输出目录文件夹名称可自己设定              
        "rootDir": "./src",		// 根目录文件夹名称可自己设定 
        "strict": true,
        "esModuleInterop": true, 
        "skipLibCheck": true,     
        "forceConsistentCasingInFileNames": true
      }
    }
    
    
  • After creating the root directory and output directory, modify the commands in package.json to make debugging easier;

    {
          
          
      "name": "ts-node",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
          
          
          // 先将ts文件编译后,在执行js文件
        "start": "tsc && node dist/index.js"
      },
      "author": "",
      "license": "ISC"
    }
    
    

2. Start the project

1. Installation dependencies

1. 请求依赖
    npm install request --save-dev
    npm install @types/request --save-dev
    参考地址:https://github.com/request/request
2. 排序依赖
    npm install lodash --save-dev
    npm install @types/lodash --save-dev
3. express
    npm install express --save-dev
    npm install @types/express --save-dev

2. Create an entity class

// User.ts
import {
    
    Repo} from "./Repo"

export class User {
    
    
  login: string;
  bio: string;
  name: string;
  avatar_url: string;
  repos : Repo[];
  constructor(responseUser: any) {
    
    
    this.login = responseUser.login;
    this.bio = responseUser.bio;
    this.name = responseUser.name;
    this.avatar_url = responseUser.avatar_url;
    this.repos = [];
  }
}
// Repo.ts
export class Repo{
    
    
    name : string;
    size : string;
    language : string;
    description : string;

    constructor(repo : any){
    
    
        this.name = repo.name;
        this.size = repo.size;
        this.language = repo.language;
        this.description = repo.description;
    }
}

3. Create a control class

  • Create control class and introduce entity class
import * as request from "request";
import {
    
     User } from "./User";
import {
    
     Repo } from "./Repo";
const config = {
    
    
  headers: {
    
    
    "User-Agent": "request",
  },
  json: true,
};

export class GithubApiService {
    
    
  getUserInfo(username: string, callback: (user: User) => void) {
    
    
    request.get(
      `https://api.github.com/users/${
      
      username}`,
      config,
      (err: any, res: any, body: any) => {
    
    
        let user: User = new User(body);
        callback(user);
      }
    );
  }
  getReposInfo(username: string, callback: any) {
    
    
    request.get(
      `https://api.github.com/users/${
      
      username}/repos`,
      config,
      (err: any, res: any, body: any) => {
    
    
        let repo: Repo[] = body.map((repo: any) => new Repo(repo));
        callback(repo);
      }
    );
  }
}

4. Instantiation

import {
    
     GithubApiService } from "./GithubApiService";
import {
    
     User } from "./User";
import {
    
     Repo } from "./Repo";
import * as Lodash from "lodash";
import express from "express";
import url from "url"

// 使用express
const app = express();

app.get("/github", (req, res) => {
    
    
    // 获取url参数
  let username : any= url.parse(req.url,true).query.username;  
  let api: GithubApiService = new GithubApiService();
  api.getUserInfo(username, (user: User) => {
    
    
    api.getReposInfo(user.login, (repos: Repo[]) => {
    
    
      // 从大到小排序
      let sortRepos = Lodash.sortBy(repos, [(repo: Repo) => repo.size * -1]);
      user.repos = sortRepos;
      res.send(user);
    });
  });
});
// 监听事件
app.listen(3000, () => {
    
    
  console.log("sever start at 3000");
});

3. Project analysis

  1. This project uses the GitHub interface to obtain information about the corresponding user;
  2. The first is to construct the Userentity class to save the user's basic information;
  3. Since each item in the user's warehouse is also an entity, an Repoentity class is reconstructed to save the basic information of the item;
  4. Then create a control class GithubApiService, introduce requestdependencies, obtain user information by requesting GitHub's api, and save the user information to Useran instance of the class;
  5. Then request the warehouse information, create Repoan array of instances of the class, and store each item information into the array through map mapping;
  6. Finally, the view layer introduces Userclasses, Repoclasses, and GithubApiServiceinterfaces;
  7. First construct an interface instance, call the getUserInfomethod to obtain the corresponding usernameuser information, then call the getReposInfomethod to obtain the warehouse information, and save it to the reposparameters of the user instance ;
  8. In order to make the warehouse project more orderly, lodashmodules can be introduced , sorted sortByaccording to the size sizeof the project through the method repos, and then stored in the user instance;
  9. To expose the interface to the browser, you can import expressmodules and urlmodules, create an app instance, get the parameters of the url username, pass in the getUserInfomethod, and put the result in the method res.send;
  10. Finally, listen to the app.

Four, project summary

  • This project uses typescript and node to obtain the required information through an external interface and return it to the front end, which is equivalent to a small agent;
  • If you want to continue to practice, you can try to find out the attribution of the number, courier information, etc.;

Guess you like

Origin blog.csdn.net/yivisir/article/details/109824637