ES6数据模型类

go4*_*cas 18 javascript api model-view-controller models ecmascript-6

我正在尝试使用ES6类在我正在构建的API中构建数据模型(来自MySQL数据库).我不喜欢使用ORM/ODM库,因为这将是一个非常基本的简单API.但是,我很难理解如何定义这些模型.

我的数据实体(这些只是一些简化的例子):

顾客

数据模型

id
name
groupId
status (enum of: active, suspended, closed)
Run Code Online (Sandbox Code Playgroud)

私人方法

_getState(status) {
    var state = (status  == 'active' ? 'good' : 'bad');
    return state;
}
Run Code Online (Sandbox Code Playgroud)

要求

我希望能够做到:

  • findById:提供单个customer.id,返回该特定客户的数据,即 SELECT * FROM customers WHERE id = ?

  • findByGroupId:提供group.id,返回属于该组的所有客户(在一个对象数组中)的数据,即 SELECT * FROM customers WHERE groupId = ?

响应有效负载

对于每个客户对象,我想要返回这样的JSON:

findById(1);:

[{
    "id" : 1,
    "name" : "John Doe",
    "groupId" : 2,
    "status" : "active",
    "state" : "good"
}]
Run Code Online (Sandbox Code Playgroud)

findByGroupId(2);:

[{
    "id" : 1,
    "name" : "John Doe",
    "groupId" : 2,
    "status" : "active",
    "state" : "good"
},
{
    "id" : 4,
    "name" : "Pete Smith",
    "groupId" : 2,
    "status" : "suspended",
    "state" : "bad"
}]
Run Code Online (Sandbox Code Playgroud)

数据模型

id
title
Run Code Online (Sandbox Code Playgroud)

要求

我希望能够做到:

  • findById:提供单个group.id,返回该特定组的数据,即 SELECT * FROM groups WHERE id = ?

响应有效负载

对于每个组对象,我想像这样返回JSON:

findById(2);:

{
    "id" : 2,
    "title" : "This is Group 2",
    "customers" : [{
        "id" : 1,
        "name" : "John Doe",
        "groupId" : 2,
        "status" : "active",
        "state" : "good"
    },
    {
        "id" : 4,
        "name" : "Pete Smith",
        "groupId" : 2,
        "status" : "suspended",
        "state" : "bad"
    }]
}
Run Code Online (Sandbox Code Playgroud)


要求:

  • 必须使用ES6类
  • 每个模型都在自己的文件中(例如customer.js)进行导出


问题:

我的主要问题是:

  1. 我在哪里定义数据结构,包括需要数据转换的字段,使用私有方法(例如_getState())
  2. 如若findById,findByGroupId等在类的范围内定义的?或者,这些应该通过单独的方法(在与该类相同的文件中)来实例化对象吗?
  3. 我应该如何处理其中一个对象是其他的,比如返回一个孩子的情况下,客户属于一个对象对象的对象在一个阵列findById
  4. 应该在哪里定义连接到DB的SQL查询?在getById,getByGroupId等?

UPDATE!

这就是我想出的 - (如果有人可以评论和评论,那会很棒):

客户模型

'use strict';

class Cust {
  constructor (custData) {
    this.id = custData.id;
    this.name = custData.name;
    this.groupId = custData.groupId;
    this.status = custData.status;
    this.state = this._getState(custData.status);
  }

  _getState(status) {
    let state = (status  == 'active' ? 'good' : 'bad');
    return state;
  }
}

exports.findById = ((id) => {
  return new Promise ((resolve, reject) => {
    let custData = `do the MySQL query here`;
    let cust = new Cust (custData);
    let Group = require(appDir + process.env.PATH_API + process.env.PATH_MODELS + 'group');
    Group.findById(cust.groupId).then(
      (group) => {
        cust.group = group;
        resolve (cust)
      },
      (err) => {
        resolve (cust);
      }
    );
  });
});
Run Code Online (Sandbox Code Playgroud)

GROUP模型

'use strict';

class Group {
  constructor (groupData) {
    this.id = groupData.id;
    this.title = groupData.title;
  }
}

exports.findById = ((id) => {
  return new Promise ((resolve, reject) => {
    let groupData = `do the MySQL query here`;
    if (id != 2){
      reject('group - no go');
    };
    let group = new Group (groupData);
    resolve (group);
  });
});
Run Code Online (Sandbox Code Playgroud)

CUSTOMER控制器(实例化客户模型)

'use strict';

var Cust = require(appDir + process.env.PATH_API + process.env.PATH_MODELS + 'cust');

class CustController {
  constructor () {
  }

  getCust (req, res) {
    Cust.findById(req.params.id).then(
      (cust) => {
        res(cust);
      },
      (err) => {
        res(err);
      }
    )
  }
}

module.exports = CustController;
Run Code Online (Sandbox Code Playgroud)

这似乎运作良好,我已经能够使用Class,Promiselet使其更加友好的ES6.

所以,我想对我的方法有所了解.此外,我在这种情况下正确使用exportrequired功能?

Nav*_*uja 5

这是另一种方法,

我将在哪里定义数据结构,包括需要数据转换的字段,使用私有方法(例如 _getState())

您应该在扩展顶级模型的模型类中定义这些字段和关系。例子:

class Group extends Model {
    attributes() {
        return {
            id: {
                type: 'integer',
                primary: true
            },
            title: {
                type: 'string'
            }
        };
    }

    relationships() {
        return {
            'Customer': {
                type: 'hasMany',
                foreignKey: 'groupId'
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

findById、findByGroupId 等是否应该在类的范围内定义?或者,是否应该通过单独的方法(与类在同一个文件中)来实例化对象?

而不是findByAttribute(attr)在模型示例中使用许多函数:

static findByAttribute(attr) {
    return new Promise((resolve, reject) => {
        var query = this._convertObjectToQueriesArray(attr);
        query = query.join(" and ");
        let records = `SELECT * from ${this.getResourceName()} where ${query}`;
        var result = this.run(records);
        // Note: Only support 'equals' and 'and' operator
        if (!result) {
            reject('Could not found records');
        } else {
            var data = [];
            result.forEach(function(record) {
                data.push(new this(record));
            });
            resolve(data);
        }
    });
}

/**
 * Convert Object of key value to sql filters
 * 
 * @param  {Object} Ex: {id:1, name: "John"}
 * @return {Array of String} ['id=1', 'name=John']
 */
static _convertObjectToQueriesArray(attrs) {
    var queryArray = [];
    for (var key in attrs) {
        queryArray.push(key + " = " + attrs[key]);
    }
    return queryArray;
}

/**
 * Returns table name or resource name.
 * 
 * @return {String}
 */
static getResourceName() {
    if (this.resourceName) return this.resourceName();
    if (this.constructor.name == "Model") {
        throw new Error("Model is not initialized");
    }
    return this.constructor.name.toLowerCase();
}
Run Code Online (Sandbox Code Playgroud)

我应该如何处理一个对象是另一个对象的子对象的情况,例如,将属于 Group 对象的 Customer 对象作为 Group 的 findById 中的对象数组返回?

在关系的情况下,你应该有像 findRelations、getRelatedRecords 这样的方法。

var customer1 = new Customer({ id: 1, groupId: 3});
customer1.getRelatedRecords('Group');

class Model {
 ...

  getRelatedRecords(reln) {
    var targetRelationship = this.relationships()[reln];
    if (!targetRelationship) {
        throw new Error("No relationship found.");
    }
    var primaryKey = this._getPrimaryKey();

    var relatedObject = eval(reln);
    var attr = {};
    if (targetRelationship.type == "hasOne") {
        console.log(this.values);
        attr[relatedObject.prototype._getPrimaryKey()] = this.values[targetRelationship.foreignKey];
    } else if (targetRelationship.type == "hasMany") {
        attr[targetRelationship.foreignKey] = this.values[this._getPrimaryKey()];
    }

    relatedObject.findByAttribute(attr).then(function(records) {
        // this.values[reln] = records;
    });
   }
 ...
}
Run Code Online (Sandbox Code Playgroud)

应该在哪里定义将连接到数据库的 SQL 查询?在 getById、getByGroupId 等中?

这很棘手,但由于您希望解决方案简单,因此将查询放在您的 find 方法中。理想的情况是拥有自己的 QueryBuilder 类。

检查以下完整代码,解决方案功能不全,但您明白了。我还在模型中添加了引擎变量,您可以使用它来增强获取机制。所有其他设计理念都取决于您的想象力:)

完整代码:

class Group extends Model {
    attributes() {
        return {
            id: {
                type: 'integer',
                primary: true
            },
            title: {
                type: 'string'
            }
        };
    }

    relationships() {
        return {
            'Customer': {
                type: 'hasMany',
                foreignKey: 'groupId'
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)