Reputation: 31
I'm trying to setup a message collection in ArangoDB that timestamps when the message was entered. However, when I setup the model in foxx it won't work if I set joi.date()
or joi.date().timestamp()
in the model schema.
I've tried to use the example in the joi documentation and convert it for use from the test examples.
'use strict';
var Foxx = require('org/arangodb/foxx');
var joi = require('joi');
var now = new Date();
var javascriptTimestamp = now.getTime();
var unixTimestamp = now.getTime() / 1000;
class TestMessage extends Foxx.Model {
}
TestMessage.prototype.schema = joi.object().options({abortEarly: false}).keys({
unix: joi.date().timestamp('unix'),
message: joi.string()
});
TestMessage.prototype.beforeUpdate = function() {
this.set({unix: now.getTime()});
};
module.exports = TestMessage;
When I save this and go to test it, the model won't show up or respond to anything on the development page.
How can I get this to set Date and or timestamps correctly?
The only other thing I could do is use AQL directly, but I still don't understand how to integrate that into the controller yet, and I'm hoping there's a simple solution.
Upvotes: 1
Views: 226
Reputation: 10902
The problem with date types in joi is that date objects are not supported in JSON, so the representation of the data in the database and in the request will not match up (you expect a millisecond timestamp but internally the Date will be stored as a JSON date string).
Try using joi.date().iso()
instead if you need to be able to convert date values into date objects in your service. The iso variant will parse the format used by JSON.stringify
so the data will survive the roundtrip:
let isoDate = JSON.parse(JSON.stringify(new Date());
let result = joi.date().iso().validate(isoDate);
let joiDate = JSON.parse(JSON.stringify(result.value));
assert.equal(isoDate, joiDate);
You should also use the function-based Model extension rather than the class-based syntax. The class-based syntax was reverted due to engine limitations although the documentation apparently hasn't been fully adjusted yet:
const Foxx = require('org/arangodb/foxx');
const TestMessage = Foxx.Model.extends({
schema: {/* ... */}
});
Upvotes: 3