我是strongloop的绿地。我的datasources.json配置如下:
"platformDB": {
"host": "localhost",
"port": 3306,
"database": "way",
"username": "root",
"password": "root",
"name": "platformDB",
"connector": "mysql"
},
和UserAccount是我的一个模型,如下:
"name": "UserAccount",
"plural": "user",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"id": {
"type": "number",
"required": false
},
"accountName": {
"type": "string",
"required": false
},
"roleName": {
"type": "string",
"required": false
},
"accessToken": {
"type": "string",
"required": false
},
"loginTime": {
"type": "date",
"required": false,
"mysql": {
"dataType": "datetime"
}
}
当我调用UserAccount.Create和userAccount.findbyid函数时,其结果还可以。但是,当我通过客户端工具连接MySQL数据库时,我发现" logintime"值是UTC时间。这个结果没有与其他系统组件协调,我需要本地时间。因此,我跟踪loopback-connector-mysql源代码,我在数据源中找到时区属性如下:
var options = {
host: s.host || s.hostname || 'localhost',
port: s.port || 3306,
user: s.username || s.user,
password: s.password,
timezone: s.timezone,
socketPath: s.socketPath,
charset: s.collation.toUpperCase(), // Correct by docs despite seeming odd.
supportBigNumbers: s.supportBigNumbers,
connectionLimit: s.connectionLimit
};
因此,我在我的dataSources.json,useraccount.findbyid函数结果中配置" timezone":" utc8"是eqauls to client to to client工具,但是userAccount.create函数结果仍然是UTC时间。为什么?
唯一的解决方案是修改核心文件。编辑/var/www/yourproject/node_modules/loopback-connector-mysql/lib/mysql.js
更改
function dateToMysql(val) {
return val.getUTCFullYear() + '-' +
fillZeros(val.getUTCMonth() + 1) + '-' +
fillZeros(val.getUTCDate()) + ' ' +
fillZeros(val.getUTCHours()) + ':' +
fillZeros(val.getUTCMinutes()) + ':' +
fillZeros(val.getUTCSeconds());
function fillZeros(v) {
return v < 10 ? '0' + v : v;
}
}
to
***function dateToMysql(val) {
return val.getFullYear() + '-' +
fillZeros(val.getMonth() + 1) + '-' +
fillZeros(val.getDate()) + ' ' +
fillZeros(val.getHours()) + ':' +
fillZeros(val.getMinutes()) + ':' +
fillZeros(val.getSeconds());
function fillZeros(v) {
return v < 10 ? '0' + v : v;
}
}***
它将节省您的时间不要忘记投票; - )
您还可以通过在DataSource JSON配置中添加时区条目:
来设置API正在运行的服务器的时区datasources.json:
{
"mysqlDS": {
"name": "mysqlDS",
"connector": "mysql",
"host": "localhost",
"port": 3306,
"database": "dbname",
"username": "root",
"password": "",
"timezone": "UTC"
}
}
然后可以在datasources.local.js中使用env vars在vars中的生产envs上覆盖。
datasources.local.js:
module.exports = {
"mysqlDS": {
host : process.env.APP_MYSQL_HOST,
port : process.env.APP_MYSQL_PORT,
database: process.env.APP_MYSQL_DB,
username: process.env.APP_MYSQL_USER,
password: process.env.APP_MYSQL_PW,
timezone: process.env.APP_MYSQL_TZ
}
}
也可能不会在dataSources.json中签入,并将其作为所有Envs的部署/构建配置的一部分。