- additional functionality for DatasetController.ts

- additional validation rules like 'uniqueArray'
- additional Lucid models like BaseModel.ts for filling attributes, Title.ts, Description.ts
- npm updates for @adonisjs/core
This commit is contained in:
Kaimbacher 2023-06-22 17:20:04 +02:00
parent c4f4eff0d9
commit e0ff71b117
44 changed files with 2002 additions and 1556 deletions

119
app/Models/BaseModel.ts Normal file
View file

@ -0,0 +1,119 @@
import { BaseModel as LucidBaseModel } from '@ioc:Adonis/Lucid/Orm';
// import { ManyToManyQueryClient } from '@ioc:Adonis/Lucid/Orm';
// export class CustomManyToManyQueryClient extends ManyToManyQueryClient {
// public attach(
// relatedIds: any | any[],
// pivotAttributes: any = {},
// trx?: ReturnType<typeof this.model.transaction>
// ) {
// return super.attach(relatedIds, (row) => {
// row.pivot.fill(pivotAttributes);
// }, trx);
// }
// }
/**
* Helper to find if value is a valid Object or
* not
*/
export function isObject(value: any): boolean {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
export default class BaseModel extends LucidBaseModel {
/**
* When `fill` method is called, then we may have a situation where it
* removed the values which exists in `original` and hence the dirty
* diff has to do a negative diff as well
*/
// private fillInvoked: boolean = false;
public static fillable: string[] = [];
public fill(attributes: any, allowExtraProperties: boolean = false): this {
this.$attributes = {};
// const Model = this.constructor as typeof BaseModel;
// for (const key in attributes) {
// if (Model.fillable.includes(key)) {
// const value = attributes[key];
// if (Model.$hasColumn(key)) {
// this[key] = value;
// }
// }
// }
this.mergeFillableAttributes(attributes, allowExtraProperties);
// this.fillInvoked = true;
return this;
}
/**
* Merge bulk attributes with existing attributes.
*
* 1. If key is unknown, it will be added to the `extras` object.
* 2. If key is defined as a relationship, it will be ignored and one must call `$setRelated`.
*/
public mergeFillableAttributes(values: any, allowExtraProperties: boolean = false): this {
const Model = this.constructor as typeof BaseModel;
/**
* Merge values with the attributes
*/
if (isObject(values)) {
// Object.keys(values).forEach((key) => {
for (const key in values) {
if (Model.fillable.includes(key)) {
const value = values[key];
/**
* Set as column
*/
if (Model.$hasColumn(key)) {
this[key] = value;
continue;
}
/**
* Resolve the attribute name from the column names. Since people
* usaully define the column names directly as well by
* accepting them directly from the API.
*/
const attributeName = Model.$keys.columnsToAttributes.get(key);
if (attributeName) {
this[attributeName] = value;
continue;
}
/**
* If key is defined as a relation, then ignore it, since one
* must pass a qualified model to `this.$setRelated()`
*/
if (Model.$relationsDefinitions.has(key)) {
continue;
}
/**
* If the property already exists on the model, then set it
* as it is vs defining it as an extra property
*/
if (this.hasOwnProperty(key)) {
this[key] = value;
continue;
}
/**
* Raise error when not instructed to ignore non-existing properties.
*/
if (!allowExtraProperties) {
throw new Error(`Cannot define "${key}" on "${Model.name}" model, since it is not defined as a model property`);
}
this.$extras[key] = value;
}
}
}
return this;
}
}

View file

@ -1,52 +1,108 @@
import {
column,
BaseModel,
SnakeCaseNamingStrategy,
// computed,
manyToMany,
ManyToMany,
column,
BaseModel,
SnakeCaseNamingStrategy,
manyToMany,
ManyToMany,
belongsTo,
BelongsTo,
hasMany,
HasMany,
} from '@ioc:Adonis/Lucid/Orm';
import { DateTime } from 'luxon';
import Person from './Person';
import User from './User';
import Title from './Title';
import Description from './Description';
import License from './License';
import Subject from './Subject';
export default class Dataset extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'documents';
public static selfAssignPrimaryKey = false;
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'documents';
public static selfAssignPrimaryKey = false;
@column({ isPrimary: true })
public id: number;
@column({ isPrimary: true })
public id: number;
@column({})
public server_state: boolean;
public server_state: boolean;
@column({})
public publisherName: string;
public publisherName: string;
@column({ columnName: 'creating_corporation' })
public creatingCorporation: string;
@column.dateTime({ columnName: 'embargo_date' })
public embargoDate: DateTime;
public embargoDate: DateTime;
@column({})
public type: string;
public type: string;
@column({})
public language: string;
@column.dateTime({ columnName: 'server_date_published' })
public serverDatePublished: DateTime;
@column({})
public account_id: number | null = null;
@column.dateTime({ autoCreate: true, columnName: 'created_at' })
public createdAt: DateTime;
@column.dateTime({ columnName: 'server_date_published' })
public serverDatePublished: DateTime;
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime;
@column.dateTime({ autoCreate: true, columnName: 'created_at' })
public createdAt: DateTime;
@column.dateTime({ autoCreate: true, autoUpdate: true, columnName: 'server_date_modified' })
public updatedAt: DateTime;
@manyToMany(() => Person, {
pivotForeignKey: 'document_id',
pivotRelatedForeignKey: 'person_id',
pivotTable: 'link_documents_persons',
pivotColumns: ['role', 'sort_order', 'allow_email_contact']
})
public persons: ManyToMany<typeof Person>;
pivotForeignKey: 'document_id',
pivotRelatedForeignKey: 'person_id',
pivotTable: 'link_documents_persons',
pivotColumns: ['role', 'sort_order', 'allow_email_contact'],
})
public persons: ManyToMany<typeof Person>;
/**
* Get the account that the dataset belongs to
*/
@belongsTo(() => User, {
foreignKey: 'account_id',
})
public user: BelongsTo<typeof User>;
@hasMany(() => Title, {
foreignKey: 'document_id',
})
public titles: HasMany<typeof Title>;
@hasMany(() => Description, {
foreignKey: 'document_id',
})
public descriptions: HasMany<typeof Description>;
@manyToMany(() => License, {
pivotForeignKey: 'document_id',
pivotRelatedForeignKey: 'licence_id',
pivotTable: 'link_documents_licences',
})
public licenses: ManyToMany<typeof License>;
// public function subjects()
// {
// return $this->belongsToMany(\App\Models\Subject::class, 'link_dataset_subjects', 'document_id', 'subject_id');
// }
@manyToMany(() => Subject, {
pivotForeignKey: 'document_id',
pivotRelatedForeignKey: 'subject_id',
pivotTable: 'link_dataset_subjects',
})
public subjects: ManyToMany<typeof Subject>;
// async save(): Promise<this> {
// // Call the parent save method to persist changes to the database
// await super.save();
// return this;
// }
}

28
app/Models/Description.ts Normal file
View file

@ -0,0 +1,28 @@
import { column, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
import Dataset from './Dataset';
import BaseModel from './BaseModel';
export default class Description extends BaseModel {
public static primaryKey = 'id';
public static table = 'dataset_abstracts';
public static selfAssignPrimaryKey = false;
public static timestamps = false;
public static fillable: string[] = ['value', 'type', 'language'];
@column({})
public document_id: number;
@column()
public type: string;
@column()
public value: string;
@column()
public language: string;
@belongsTo(() => Dataset, {
foreignKey: 'document_id',
})
public dataset: BelongsTo<typeof Dataset>;
}

View file

@ -1,54 +1,55 @@
import { DateTime } from 'luxon';
import {
column,
BaseModel,
hasMany, HasMany,
// manyToMany,
// ManyToMany,
SnakeCaseNamingStrategy,
column,
BaseModel,
hasMany,
HasMany,
// manyToMany,
// ManyToMany,
SnakeCaseNamingStrategy,
} from '@ioc:Adonis/Lucid/Orm';
import HashValue from './HashValue';
export default class File extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'document_files';
public static selfAssignPrimaryKey = false;
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'document_files';
public static selfAssignPrimaryKey = false;
@column({
isPrimary: true,
})
public id: number;
@column({
isPrimary: true,
})
public id: number;
@column({})
public pathName: string;
@column()
public label: string;
@column({})
public pathName: string;
@column()
public comment: string;
public label: string;
@column()
public mimetype: string;
public comment: string;
@column()
public language: string;
public mimetype: string;
@column()
public fileSize: bigint;
public language: string;
@column()
public visibleInOai: boolean;
public fileSize: bigint;
@column()
public sortOrder: number;
public visibleInOai: boolean;
@column()
public sortOrder: number;
@column.dateTime({ autoCreate: true })
public createdAt: DateTime;
public createdAt: DateTime;
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime;
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime;
// public function hashvalues()
// {
@ -58,5 +59,5 @@ export default class File extends BaseModel {
@hasMany(() => HashValue, {
foreignKey: 'file_id',
})
public hashvalues: HasMany<typeof HashValue>;
}
public hashvalues: HasMany<typeof HashValue>;
}

View file

@ -1,41 +1,34 @@
import {
column,
BaseModel,
belongsTo,
BelongsTo,
SnakeCaseNamingStrategy,
} from '@ioc:Adonis/Lucid/Orm';
import { column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
import File from './File';
export default class HashValue extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'file_id, type';
public static table = 'file_hashvalues';
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'file_id, type';
public static table = 'file_hashvalues';
// static get primaryKey () {
// return 'type, value'
// }
static get incrementing () {
return false
}
static get incrementing() {
return false;
}
// @column({
// isPrimary: true,
// })
// public id: number;
// Foreign key is still on the same model
// @column({
// isPrimary: true,
// })
// public id: number;
// Foreign key is still on the same model
@column({})
public file_id: number;
public file_id: number;
@column({})
public type: string;
public type: string;
@column()
public value: string;
@column()
public value: string;
@belongsTo(() => File)
public file: BelongsTo<typeof File>
}
public file: BelongsTo<typeof File>;
}

View file

@ -5,6 +5,22 @@ export default class License extends BaseModel {
public static primaryKey = 'id';
public static table = 'document_licences';
public static selfAssignPrimaryKey = false;
public static timestamps = false;
public static fillable: string[] = [
'name_long',
'name',
'language',
'link_licence',
'link_logo',
'desc_text',
'desc_markup',
'comment_internal',
'mime_type',
'sort_order',
'language',
'active',
'pod_allowed',
];
@column({
isPrimary: true,

View file

@ -1,100 +1,92 @@
import {
column,
BaseModel,
manyToMany,
ManyToMany,
SnakeCaseNamingStrategy,
beforeUpdate,
beforeCreate,
} from '@ioc:Adonis/Lucid/Orm';
import { column, BaseModel, manyToMany, ManyToMany, SnakeCaseNamingStrategy, beforeUpdate, beforeCreate } from '@ioc:Adonis/Lucid/Orm';
import { DateTime } from 'luxon';
import dayjs from 'dayjs';
import Role from 'App/Models/Role';
export default class Permission extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'permissions';
public static selfAssignPrimaryKey = false;
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'permissions';
public static selfAssignPrimaryKey = false;
@column({
isPrimary: true,
})
public id: number;
@column({
isPrimary: true,
})
public id: number;
@column({})
public role_id: number;
@column({})
public role_id: number;
@column({})
public display_name: string;
@column({})
public display_name: string;
@column({})
public name: string;
@column({})
public name: string;
@column({})
public description: string;
@column({})
public description: string;
@column.dateTime({
serialize: (value: Date | null) => {
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
autoCreate: true,
})
public created_at: DateTime;
@column.dateTime({
serialize: (value: Date | null) => {
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
autoCreate: true,
})
public created_at: DateTime;
@column.dateTime({
serialize: (value: Date | null) => {
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
autoCreate: true,
autoUpdate: true,
})
public updated_at: DateTime;
@column.dateTime({
serialize: (value: Date | null) => {
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
autoCreate: true,
autoUpdate: true,
})
public updated_at: DateTime;
@beforeCreate()
@beforeUpdate()
public static async resetDate(role) {
role.created_at = this.formatDateTime(role.created_at);
role.updated_at = this.formatDateTime(role.updated_at);
}
@beforeCreate()
@beforeUpdate()
public static async resetDate(role) {
role.created_at = this.formatDateTime(role.created_at);
role.updated_at = this.formatDateTime(role.updated_at);
}
// public static boot() {
// super.boot()
// public static boot() {
// super.boot()
// this.before('create', async (_modelInstance) => {
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
// })
// this.before('update', async (_modelInstance) => {
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
// })
// }
// this.before('create', async (_modelInstance) => {
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
// })
// this.before('update', async (_modelInstance) => {
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
// })
// }
private static formatDateTime(datetime) {
let value = new Date(datetime);
return datetime
? value.getFullYear() +
'-' +
(value.getMonth() + 1) +
'-' +
value.getDate() +
' ' +
value.getHours() +
':' +
value.getMinutes() +
':' +
value.getSeconds()
: datetime;
}
private static formatDateTime(datetime) {
let value = new Date(datetime);
return datetime
? value.getFullYear() +
'-' +
(value.getMonth() + 1) +
'-' +
value.getDate() +
' ' +
value.getHours() +
':' +
value.getMinutes() +
':' +
value.getSeconds()
: datetime;
}
// @belongsTo(() => Role)
// public role: BelongsTo<typeof Role>;
// @belongsTo(() => Role)
// public role: BelongsTo<typeof Role>;
@manyToMany(() => Role, {
pivotForeignKey: 'permission_id',
pivotRelatedForeignKey: 'role_id',
pivotTable: 'role_has_permissions',
})
public roles: ManyToMany<typeof Role>;
@manyToMany(() => Role, {
pivotForeignKey: 'permission_id',
pivotRelatedForeignKey: 'role_id',
pivotTable: 'role_has_permissions',
})
public roles: ManyToMany<typeof Role>;
}

View file

@ -1,83 +1,79 @@
import {
column,
BaseModel,
SnakeCaseNamingStrategy,
computed,
manyToMany,
ManyToMany,
} from '@ioc:Adonis/Lucid/Orm';
import { column, SnakeCaseNamingStrategy, computed, manyToMany, ManyToMany } from '@ioc:Adonis/Lucid/Orm';
import { DateTime } from 'luxon';
import dayjs from 'dayjs';
import Dataset from './Dataset';
import BaseModel from './BaseModel';
export default class Person extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'persons';
public static selfAssignPrimaryKey = false;
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'persons';
public static selfAssignPrimaryKey = false;
// only the academic_title, email, first_name, identifier_orcid, last_name and name_type attributes are allowed to be mass assigned.
public static fillable: string[] = ['academic_title', 'email', 'first_name', 'identifier_orcid', 'last_name', 'name_type'];
@column({
isPrimary: true,
})
public id: number;
@column({})
public academicTitle: string;
@column()
public email: string;
@column({})
public firstName: string;
@column({})
public lastName: string;
@column({})
public identifierOrcid: string;
@column({})
public status: boolean;
@column({})
public nameType: string;
@column.dateTime({
serialize: (value: Date | null) => {
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
autoCreate: true,
})
public createdAt: DateTime;
@computed({
serializeAs: 'name'
@column({
isPrimary: true,
})
public get fullName() {
return `${this.firstName} ${this.lastName}`;
}
public id: number;
@column({ columnName: 'academic_title' })
public academicTitle: string;
@column()
public email: string;
@column({})
public firstName: string;
@column({})
public lastName: string;
@column({})
public identifierOrcid: string;
@column({})
public status: boolean;
@column({})
public nameType: string;
@column.dateTime({
serialize: (value: Date | null) => {
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
autoCreate: true,
})
public createdAt: DateTime;
@computed({
serializeAs: 'name',
})
public get fullName() {
return `${this.firstName} ${this.lastName}`;
}
// @computed()
// public get progress(): number {
// return 50;
// }
// public get progress(): number {
// return 50;
// }
// @computed()
// public get created_at() {
// return '2023-03-21 08:45:00';
// }
// public get created_at() {
// return '2023-03-21 08:45:00';
// }
@computed()
public get datasetCount() {
const stock = this.$extras.datasets_count //my pivot column name was "stock"
return stock
}
const stock = this.$extras.datasets_count; //my pivot column name was "stock"
return stock;
}
@manyToMany(() => Dataset, {
pivotForeignKey: 'person_id',
pivotRelatedForeignKey: 'document_id',
pivotTable: 'link_documents_persons',
pivotColumns: ['role', 'sort_order', 'allow_email_contact']
})
public datasets: ManyToMany<typeof Dataset>;
@manyToMany(() => Dataset, {
pivotForeignKey: 'person_id',
pivotRelatedForeignKey: 'document_id',
pivotTable: 'link_documents_persons',
pivotColumns: ['role', 'sort_order', 'allow_email_contact'],
})
public datasets: ManyToMany<typeof Dataset>;
}

View file

@ -12,7 +12,6 @@ export default class Project extends BaseModel {
})
public id: number;
@column({})
public label: string;
@ -24,14 +23,12 @@ export default class Project extends BaseModel {
@column.dateTime({
autoCreate: true,
})
public created_at: DateTime;
})
public created_at: DateTime;
@column.dateTime({
@column.dateTime({
autoCreate: true,
autoUpdate: true
})
public updated_at: DateTime;
autoUpdate: true,
})
public updated_at: DateTime;
}

View file

@ -1,12 +1,4 @@
import {
column,
BaseModel,
SnakeCaseNamingStrategy,
manyToMany,
ManyToMany,
beforeCreate,
beforeUpdate,
} from '@ioc:Adonis/Lucid/Orm';
import { column, BaseModel, SnakeCaseNamingStrategy, manyToMany, ManyToMany, beforeCreate, beforeUpdate } from '@ioc:Adonis/Lucid/Orm';
import { DateTime } from 'luxon';
// import moment from 'moment';
@ -15,91 +7,91 @@ import User from './User';
import Permission from 'App/Models/Permission';
export default class Role extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'roles';
public static selfAssignPrimaryKey = false;
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'roles';
public static selfAssignPrimaryKey = false;
@column({
isPrimary: true,
})
public id: number;
@column({
isPrimary: true,
})
public id: number;
@column({})
public display_name: string;
@column({})
public display_name: string;
@column({})
public name: string;
@column({})
public name: string;
@column({})
public description: string;
@column({})
public description: string;
@column.dateTime({
serialize: (value: Date | null) => {
// return value ? moment(value).format('MMMM Do YYYY, HH:mm:ss') : value;
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
@column.dateTime({
serialize: (value: Date | null) => {
// return value ? moment(value).format('MMMM Do YYYY, HH:mm:ss') : value;
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
autoCreate: true,
})
public created_at: DateTime;
})
public created_at: DateTime;
@column.dateTime({
serialize: (value: Date | null) => {
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
@column.dateTime({
serialize: (value: Date | null) => {
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
},
autoCreate: true,
autoUpdate: true
})
public updated_at: DateTime;
autoUpdate: true,
})
public updated_at: DateTime;
@beforeCreate()
@beforeCreate()
@beforeUpdate()
public static async resetDate(role) {
role.created_at = this.formatDateTime(role.created_at);
role.updated_at = this.formatDateTime(role.updated_at);
}
public static async resetDate(role) {
role.created_at = this.formatDateTime(role.created_at);
role.updated_at = this.formatDateTime(role.updated_at);
}
// public static boot() {
// super.boot();
// public static boot() {
// super.boot();
// this.before('create', async (_modelInstance) => {
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
// });
// this.before('update', async (_modelInstance) => {
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
// });
// }
// this.before('create', async (_modelInstance) => {
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
// });
// this.before('update', async (_modelInstance) => {
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
// });
// }
private static formatDateTime(datetime) {
let value = new Date(datetime);
return datetime
? value.getFullYear() +
'-' +
(value.getMonth() + 1) +
'-' +
value.getDate() +
' ' +
value.getHours() +
':' +
value.getMinutes() +
':' +
value.getSeconds()
: datetime;
}
private static formatDateTime(datetime) {
let value = new Date(datetime);
return datetime
? value.getFullYear() +
'-' +
(value.getMonth() + 1) +
'-' +
value.getDate() +
' ' +
value.getHours() +
':' +
value.getMinutes() +
':' +
value.getSeconds()
: datetime;
}
@manyToMany(() => User, {
pivotForeignKey: 'role_id',
pivotRelatedForeignKey: 'account_id',
pivotTable: 'link_accounts_roles',
})
public users: ManyToMany<typeof User>;
@manyToMany(() => User, {
pivotForeignKey: 'role_id',
pivotRelatedForeignKey: 'account_id',
pivotTable: 'link_accounts_roles',
})
public users: ManyToMany<typeof User>;
@manyToMany(() => Permission, {
pivotForeignKey: 'role_id',
pivotRelatedForeignKey: 'permission_id',
pivotTable: 'role_has_permissions',
})
public permissions: ManyToMany<typeof Permission>;
@manyToMany(() => Permission, {
pivotForeignKey: 'role_id',
pivotRelatedForeignKey: 'permission_id',
pivotTable: 'role_has_permissions',
})
public permissions: ManyToMany<typeof Permission>;
}

28
app/Models/Title.ts Normal file
View file

@ -0,0 +1,28 @@
import { column, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
import Dataset from './Dataset';
import BaseModel from './BaseModel';
export default class Title extends BaseModel {
public static primaryKey = 'id';
public static table = 'dataset_titles';
public static selfAssignPrimaryKey = false;
public static timestamps = false;
public static fillable: string[] = ['value', 'type', 'language'];
@column({})
public document_id: number;
@column()
public type: string;
@column()
public value: string;
@column()
public language: string;
@belongsTo(() => Dataset, {
foreignKey: 'document_id',
})
public dataset: BelongsTo<typeof Dataset>;
}

View file

@ -1,9 +1,10 @@
import { DateTime } from 'luxon';
import { BaseModel, column, beforeSave, manyToMany, ManyToMany } from '@ioc:Adonis/Lucid/Orm';
import { BaseModel, column, beforeSave, manyToMany, ManyToMany, hasMany, HasMany } from '@ioc:Adonis/Lucid/Orm';
import Hash from '@ioc:Adonis/Core/Hash';
import Role from './Role';
import Database from '@ioc:Adonis/Lucid/Database';
import Config from '@ioc:Adonis/Core/Config';
import Dataset from './Dataset';
// export default interface IUser {
// id: number;
@ -22,82 +23,87 @@ const roleTable = Config.get('rolePermission.role_table', 'roles');
const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
export default class User extends BaseModel {
public static table = 'accounts';
public static table = 'accounts';
@column({ isPrimary: true })
public id: number;
@column({ isPrimary: true })
public id: number;
@column()
public login: string;
@column()
public login: string;
@column()
public email: string;
@column()
public email: string;
@column({ serializeAs: null })
public password: string;
@column({ serializeAs: null })
public password: string;
@column.dateTime({ autoCreate: true })
public createdAt: DateTime;
@column.dateTime({ autoCreate: true })
public createdAt: DateTime;
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime;
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime;
@beforeSave()
public static async hashPassword(user) {
if (user.$dirty.password) {
user.password = await Hash.make(user.password);
}
}
@beforeSave()
public static async hashPassword(user) {
if (user.$dirty.password) {
user.password = await Hash.make(user.password);
}
}
@manyToMany(() => Role, {
pivotForeignKey: 'account_id',
pivotRelatedForeignKey: 'role_id',
pivotTable: 'link_accounts_roles',
})
public roles: ManyToMany<typeof Role>;
@manyToMany(() => Role, {
pivotForeignKey: 'account_id',
pivotRelatedForeignKey: 'role_id',
pivotTable: 'link_accounts_roles',
})
public roles: ManyToMany<typeof Role>;
// https://github.com/adonisjs/core/discussions/1872#discussioncomment-132289
public async getRoles(this: User): Promise<string[]> {
const test = await this.related('roles').query();
return test.map((role) => role.name);
}
@hasMany(() => Dataset, {
foreignKey: 'account_id',
})
public datasets: HasMany<typeof Dataset>;
public async can(permissionNames: Array<string>): Promise<boolean> {
// const permissions = await this.getPermissions()
// return Acl.check(expression, operand => _.includes(permissions, operand))
const hasPermission = await this.checkHasPermissions(this, permissionNames);
return hasPermission;
}
// https://github.com/adonisjs/core/discussions/1872#discussioncomment-132289
public async getRoles(this: User): Promise<string[]> {
const test = await this.related('roles').query();
return test.map((role) => role.name);
}
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
let permissionPlaceHolder = '(';
let placeholders = new Array(permissionNames.length).fill('?');
permissionPlaceHolder += placeholders.join(',');
permissionPlaceHolder += ')';
public async can(permissionNames: Array<string>): Promise<boolean> {
// const permissions = await this.getPermissions()
// return Acl.check(expression, operand => _.includes(permissions, operand))
const hasPermission = await this.checkHasPermissions(this, permissionNames);
return hasPermission;
}
let {
rows: {
0: { permissioncount },
},
} = await Database.rawQuery(
'SELECT count("p"."name") as permissionCount FROM ' +
roleTable +
' r INNER JOIN ' +
userRoleTable +
' ur ON ur.role_id=r.id AND "ur"."account_id"=? ' +
' INNER JOIN ' +
rolePermissionTable +
' rp ON rp.role_id=r.id ' +
' INNER JOIN ' +
permissionTable +
' p ON rp.permission_id=p.id AND "p"."name" in ' +
permissionPlaceHolder +
' LIMIT 1',
[user.id, ...permissionNames]
);
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
let permissionPlaceHolder = '(';
let placeholders = new Array(permissionNames.length).fill('?');
permissionPlaceHolder += placeholders.join(',');
permissionPlaceHolder += ')';
return permissioncount > 0;
}
let {
rows: {
0: { permissioncount },
},
} = await Database.rawQuery(
'SELECT count("p"."name") as permissionCount FROM ' +
roleTable +
' r INNER JOIN ' +
userRoleTable +
' ur ON ur.role_id=r.id AND "ur"."account_id"=? ' +
' INNER JOIN ' +
rolePermissionTable +
' rp ON rp.role_id=r.id ' +
' INNER JOIN ' +
permissionTable +
' p ON rp.permission_id=p.id AND "p"."name" in ' +
permissionPlaceHolder +
' LIMIT 1',
[user.id, ...permissionNames],
);
return permissioncount > 0;
}
}
// export default User;

View file

@ -1,74 +1,74 @@
import {column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy} from '@ioc:Adonis/Lucid/Orm'
import { column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
import User from 'App/Models/User'
import Role from 'App/Models/Role'
import { DateTime } from 'luxon'
import User from 'App/Models/User';
import Role from 'App/Models/Role';
import { DateTime } from 'luxon';
// import moment from 'moment'
export default class UserRole extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy()
public static primaryKey = 'id'
public static table = 'user_roles'
public static selfAssignPrimaryKey = false
public static namingStrategy = new SnakeCaseNamingStrategy();
public static primaryKey = 'id';
public static table = 'user_roles';
public static selfAssignPrimaryKey = false;
@column({
isPrimary: true,
})
public id: number
@column({})
public user_id: number
@column({})
public role_id: number
@column({
// serialize: (value: DateTime | null) => {
// return value ? moment(value).format('lll') : value
// },
})
public created_at: DateTime
@column({
// serialize: (value: DateTime | null) => {
// return value ? moment(value).format('lll') : value
// },
})
public updated_at: DateTime
public static boot() {
super.boot()
this.before('create', async (_modelInstance) => {
_modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
_modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
@column({
isPrimary: true,
})
this.before('update', async (_modelInstance) => {
_modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
_modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
public id: number;
@column({})
public user_id: number;
@column({})
public role_id: number;
@column({
// serialize: (value: DateTime | null) => {
// return value ? moment(value).format('lll') : value
// },
})
}
public created_at: DateTime;
private static formatDateTime(datetime) {
let value = new Date(datetime)
return datetime
? value.getFullYear() +
'-' +
(value.getMonth() + 1) +
'-' +
value.getDate() +
' ' +
value.getHours() +
':' +
value.getMinutes() +
':' +
value.getSeconds()
: datetime
}
@column({
// serialize: (value: DateTime | null) => {
// return value ? moment(value).format('lll') : value
// },
})
public updated_at: DateTime;
@belongsTo(() => User)
public user: BelongsTo<typeof User>
public static boot() {
super.boot();
@belongsTo(() => Role)
public role: BelongsTo<typeof Role>
this.before('create', async (_modelInstance) => {
_modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
_modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
});
this.before('update', async (_modelInstance) => {
_modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
_modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
});
}
private static formatDateTime(datetime) {
let value = new Date(datetime);
return datetime
? value.getFullYear() +
'-' +
(value.getMonth() + 1) +
'-' +
value.getDate() +
' ' +
value.getHours() +
':' +
value.getMinutes() +
':' +
value.getSeconds()
: datetime;
}
@belongsTo(() => User)
public user: BelongsTo<typeof User>;
@belongsTo(() => Role)
public role: BelongsTo<typeof Role>;
}