backend/app/models/VersionedModel.js

50 lines
1.5 KiB
JavaScript
Raw Normal View History

const Model = require('flitter-orm/src/model/Model');
const uuid = require('uuid/v4');
class VersionedModel extends Model {
static get schema() {
return {
version_archive: [Object],
version_num: { type: Number, default: 1 },
version_create_date: { type: Date, default: () => new Date },
2020-11-02 18:10:52 +00:00
version_user_id: String,
}
}
2020-11-02 18:10:52 +00:00
async version_save(message = undefined, user_id = undefined) {
await this.new_version(message, user_id)
return this.save()
}
2020-11-02 18:10:52 +00:00
async new_version(message = undefined, user_id = undefined) {
if ( !this.version_num ) this.version_num = 1
if ( !this.version_archive ) this.version_archive = []
this.version_num += 1
this.version_create_date = new Date()
2020-11-02 18:10:52 +00:00
this.version_user_id = user_id
2020-11-02 18:31:05 +00:00
const version_data = await this.cast_to_version_data()
version_data.version_UUID = uuid()
version_data.version_message = message
this.version_archive.push(version_data)
}
async cast_to_version_data() {
const schema = this.constructor.__schema
const shallow_object = {}
for ( const prop in schema.schema ) {
if ( prop in this ) {
shallow_object[prop] = this[prop]
}
}
const data = await this.__scope_limit_save(schema.cast_to_schema(shallow_object))
delete data.version_archive
return data
}
}
module.exports = exports = VersionedModel