backend/app/models/api/db/Database.model.js
2020-03-01 15:37:52 -06:00

69 lines
1.8 KiB
JavaScript

const Model = require('flitter-orm/src/model/Model')
const uuid = require('uuid/v4')
const ColumnDef = require('./ColumnDef.model')
const Page = require('../Page.model')
const Node = require('../Node.model')
const ActiveScope = require('../../scopes/Active.scope')
/*
* Database Model
* -------------------------------------------------------------
* Put some description here!
*/
class Database extends Model {
static get schema() {
// Return a flitter-orm schema here.
return {
Name: String,
NodeId: String,
PageId: String,
ColumnIds: [String],
UUID: { type: String, default: () => uuid() },
Active: { type: Boolean, default: true },
}
}
static scopes = [new ActiveScope]
static async visible_by_user(user) {
const page_ids = (await Page.visible_by_user(user)).map(x => x.UUID)
return this.find({PageId: {$in: page_ids}})
}
async is_accessible_by(user, mode = 'view') {
const page = await this.page
return page.is_accessible_by(user, mode)
}
async get_columns() {
const cols = await ColumnDef.find({DatabaseId: this.UUID})
const assoc_cols = {}
cols.forEach(col => assoc_cols[col.UUID] = col)
return this.ColumnIds.map(x => assoc_cols[x])
}
get page() {
return this.belongs_to_one(Page, 'PageId', 'UUID')
}
get node() {
return this.belongs_to_one(Node, 'NodeId', 'UUID')
}
async delete() {
this.Active = false
await this.save()
}
to_api_object() {
return {
name: this.Name,
uuid: this.UUID,
page_id: this.PageId,
column_ids: this.ColumnIds,
}
}
}
module.exports = exports = Database