Below is my Node.js code running in my REST API. It gets the data from a database and return to the caller application.
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)
}
});
}
};
This gives the following output. It is a 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"
}
]
The caller app accepts the created_date
and last_updated
fields as TimeStamps so the field data type needs to be int
. For your information, the caller app is a Flutter app and its model
class looks like this.
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);
}
My question is, from my Node.JS code, how can I return the same result only with created_date
and last_updated
changed as TimeStamp of type int
?