【发布时间】:2021-11-18 05:59:00
【问题描述】:
以下是在我的 REST API 中运行的 Node.js 代码。它从数据库中获取数据并返回给调用者应用程序。
const mysql = require('mysql2');
const errorCodes = require('source/error-codes');
const PropertiesReader = require('properties-reader');
const prop = PropertiesReader('properties.properties');
const con = mysql.createConnection({
host: prop.get('server.host'),
user: prop.get("server.username"),
password: prop.get("server.password"),
port: prop.get("server.port"),
database: prop.get("server.dbname")
});
exports.getUserByID = (event, context, callback) => {
const params = event.queryStringParameters;
if (!params || params.id == null) {
context.callbackWaitsForEmptyEventLoop = false;
var response = errorCodes.missing_parameters;
callback(null, response)
}
else {
const { id } = event.queryStringParameters;
console.log("id", id);
//log.console("id",id);
// allows for using callbacks as finish/error-handlers
context.callbackWaitsForEmptyEventLoop = false;
const sql = "select * from user where iduser = ?";
con.execute(sql, [id], function (err, result) {
if (err) {
console.log(err);
var response = errorCodes.internal_server_error;
callback(null, response);
}
else {
var response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify(result),
"isBase64Encoded": false
};
callback(null, response)
}
});
}
};
这给出了以下输出。这是一个JSON Array。
[
{
"iduser": 2,
"first_name": "John",
"last_name": "Vector",
"profile_picture": "https://link",
"email": "john@test.com",
"phone": "0000000000",
"is_disabled": 0,
"created_date": "2021-07-28T00:00:00.000Z",
"last_updated": "2021-07-28T00:00:00.000Z",
"uid": "2"
}
]
调用方应用接受created_date 和last_updated 字段作为时间戳,因此字段数据类型需要为int。供您参考,调用方应用是 Flutter 应用,其 model 类如下所示。
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
int? idUser;
String? uid;
String? firstName;
String? lastName;
String? profilePicture;
String? email;
String? phone;
int? isDisabled;
int? createdDate;
int? lastUpdated;
User(
{this.idUser,
this.uid,
this.firstName,
this.lastName,
this.profilePicture,
this.email,
this.isDisabled,
this.createdDate,
this.lastUpdated,
this.phone});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
我的问题是,从我的 Node.JS 代码中,如何仅将 created_date 和 last_updated 更改为类型为 int 的 TimeStamp 才能返回相同的结果?
【问题讨论】:
-
你的 MySQL 查询中的 UNIX_TIMESTAMP 方法有帮助吗?
-
@rosh-dev:介意给我举个例子吗?
-
从用户中选择 UNIX_TIMESTAMP(created_date),UNIX_TIMESTAMP(last_updated)。此查询以 int 形式返回日期时间。但是在颤振方面有一个问题。如果您希望我可以在答案部分展示我在 nodejs 和颤振之间处理日期时间的方式。但在我的模型类中,我使用日期时间(不是 int)。
标签: javascript node.js json flutter unix-timestamp