0

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 ?

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • does UNIX_TIMESTAMP method in your MySQL query will help? – rosh-dev851 Sep 25 '21 at 06:36
  • @rosh-dev: Mind giving me an example? – PeakGen Sep 25 '21 at 09:29
  • select UNIX_TIMESTAMP(created_date),UNIX_TIMESTAMP(last_updated) from user. this query returns datetime as an int. but there is a catch in the flutter side. If you wish I can show my way of handling datetime between nodejs and flutter in the answer section. but in my model class I use datetime (not int). – rosh-dev851 Sep 25 '21 at 12:12

3 Answers3

0

Excuse me if I didn't understand your need, but why don't you simply get the time of this well-recognized date format ?

new Date("2021-07-28T00:00:00.000Z").getTime()

seems ok.

Philippe
  • 1,134
  • 12
  • 22
  • This to be applied in where? JS or Flutter? – PeakGen Sep 25 '21 at 09:25
  • > 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 ? You suggest you can take control of the JS part, this is an approach to achieve your goal by an example. @ssc-hrep3 even gives you a complete js function :) – Philippe Sep 25 '21 at 09:45
0

You can map over your JSON Array and convert dates to timestamp.

const convertToTimestamp = function (date) {
  return new Date(date).getTime()
}

const reformattedOutput = array.map((item) => {
  return {
    ...item,
    "created_date": convertToTimestamp(item.created_date),
    "last_updated": convertToTimestamp(item.last_updated)
  }
})
fsefidabi
  • 153
  • 1
  • 12
  • Convert JSON array in where? In my app or in REST API? – PeakGen Sep 25 '21 at 09:26
  • You can write it before using your output. If you call this API several times, you can use hooks or middlewares, based on what framework you're using. – fsefidabi Sep 25 '21 at 12:43
0

MySQL is a string based protocol. If you want to always convert a date string into something else, you can use a typeCast and conditionally change the value.

Here is an example of a typecast I just found:

const db = mysql.createConnection({
    typeCast: function (field, next) {
        if (field.type == 'DATE') {
            return field.string();
        }
        return next();
    }
})
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
  • Thank you. But i am really not clear how to apply this into my situation. FYI, I am not a JS guy. Can you help by showing how to apply this to my code? – PeakGen Sep 25 '21 at 09:24