【问题标题】:Restful API typescript and promisesRestful API 打字稿和承诺
【发布时间】:2019-08-24 23:02:25
【问题描述】:

如何使用 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 来实现?

【问题讨论】:

  • 最后我检查了没有“抽象”方法。你在说protected 吗?
  • 对不起,我搜查了帖子我并不是说它是抽象的字面意思,我的意思是它非常基础,可以使用任何数据库来实现。
  • 如何为任何类型的数据库构建 API 是一个过于宽泛的问题,正如 help center 中所述

标签: javascript typescript express promise async-await


【解决方案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}`;
    });

【讨论】:

    猜你喜欢
    • 2020-03-10
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多