宁静的API打字稿和承诺

时间:2019-04-03 12:06:50

标签: javascript typescript express promise async-await

如何创建带有CRUD方法的类,API定义为: 它创建,获取,更新和删除任务。 不接收请求和响应。您必须接收经过转换和验证的数据。  不要直接将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来实现该方法?

1 个答案:

答案 0 :(得分:1)

这里有一些样板代码,可帮助您开始为任务创建数据库层。使用总是使用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}`;
    });