首页 > 解决方案 > Restful API 打字稿和承诺

问题描述

如何使用 CRUD 方法创建一个类,API 定义:它创建、获取、更新和删除任务。不接收 Request 和 Response 。您必须接收经过转换和验证的数据。不要直接向客户端响应 json。你必须承诺。

public updateTask (_task: itask) {
      return new Promise < ITask > ((resolve, reject) => {
        // save
      });
    }

    public deleteTask (_task: itask) {
      return new Promise < ITask > ((resolve, reject) => {
        // delete
      });
    }

谁能给我一个关于如何构建这种宁静的 api 方法的例子,然后可以使用任何 db sql 或 noSQL 来实现?

标签: javascripttypescriptexpresspromiseasync-await

解决方案


下面是一些样板代码,可帮助您开始为任务创建 DB 层。使用始终使用 Promises 的 async/await 并使您的代码更加程序化且更易于推理。那是你想要的吗?

interface ITask {
    id: number;
    a: string;
    b: number;
}

class TasksManager {

    private _dbConnection; // a DB Connection object
    private _connected: boolean;
    private _dbUsername: string;
    private _dbPasssword: string;

    constructor() {
        // do init stuff here for the DB
    }

    private async connect() {
        // actual code that connects to the DB
    }

    private async diconnect() {
        // actual code that disconnects from the DB
    }

    private async doQuery(querystring: string) {

        // use the dbconnection object to do the query and get the results
        let a: Array<string> = [];

        return a; // this actually returns a Promise as the function is 'async'
    }


/*********************
 *      PUBLIC API
 *********************/

    set username(v: string) {
        this._dbUsername = v;
    }

    set password(v: string) {
        this._dbPasssword = v;
    }

    public async deleteTask(t: ITask) {
        if (!this._connected) {
            await this.connect();
        }

        // create the querystring and execute the query
        let qstring = "DELETE * FROM TASKS WHERE ID = " + t.id;


        let result = await this.doQuery(qstring); 

        // do stuff with the results

        if (result[0] == "OK") {
            return true; // this actually returns a Promise as the function is 'async'
        } else {
            return false; // this actually returns a Promise as the function is 'async'
        }

    }

    public async updateTask(t: ITask) {
        if (!this._connected) {
            await this.connect();
        }

        // code to update task.....

        let result = await this.doQuery("UPDATE TASKS ...."); // this blocks until the query returns

        if (result[0] == "OK") {
            return true; // this actually returns a Promise as the function is 'async'
        } else {
            return false; // this actually returns a Promise as the function is 'async'
        }
    }

    public async createTask(a: string, b: number) {
        if (!this._connected) {
            await this.connect();
        }

        // code to create querystring and do the query to create the task.....
        let result = await this.doQuery("INSERT INTO ...."); // this blocks until the query returns

        if (result[0] == "OK") {
            return true; // this actually returns a Promise as the function is 'async'
        } else {
            return false; // this actually returns a Promise as the function is 'async'
        }
    }
}


// create the manager
let taskManager = new TasksManager();

// create new task
taskManager.createTask("one", 2).then((result) => {
        if (result == true) {
        console.log("task created!!");
        }
    })
    .catch((err) => {
        throw `Failed to create task. reason: ${err}`;
    });

推荐阅读