- additional functionality for DatasetController.ts
All checks were successful
CI Pipeline / japa-tests (push) Successful in 47s
All checks were successful
CI Pipeline / japa-tests (push) Successful in 47s
- 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:
parent
c4f4eff0d9
commit
e0ff71b117
44 changed files with 2002 additions and 1556 deletions
|
@ -1,17 +1,17 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
|
||||
export default class HomeController {
|
||||
public async index({}: HttpContextContract) {}
|
||||
public async index({}: HttpContextContract) {}
|
||||
|
||||
public async create({}: HttpContextContract) {}
|
||||
public async create({}: HttpContextContract) {}
|
||||
|
||||
public async store({}: HttpContextContract) {}
|
||||
public async store({}: HttpContextContract) {}
|
||||
|
||||
public async show({}: HttpContextContract) {}
|
||||
public async show({}: HttpContextContract) {}
|
||||
|
||||
public async edit({}: HttpContextContract) {}
|
||||
public async edit({}: HttpContextContract) {}
|
||||
|
||||
public async update({}: HttpContextContract) {}
|
||||
public async update({}: HttpContextContract) {}
|
||||
|
||||
public async destroy({}: HttpContextContract) {}
|
||||
public async destroy({}: HttpContextContract) {}
|
||||
}
|
||||
|
|
|
@ -8,197 +8,207 @@ import { RenderResponse } from '@ioc:EidelLev/Inertia';
|
|||
// import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
|
||||
export default class UsersController {
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
const page = request.input('page', 1);
|
||||
// const limit = 10
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
const page = request.input('page', 1);
|
||||
// const limit = 10
|
||||
|
||||
let users: ModelQueryBuilderContract<typeof User, User> = User.query();
|
||||
let users: ModelQueryBuilderContract<typeof User, User> = User.query();
|
||||
|
||||
if (request.input('search')) {
|
||||
// users = users.whereRaw('name like %?%', [request.input('search')])
|
||||
const searchTerm = request.input('search');
|
||||
users.where('login', 'ilike', `%${searchTerm}%`);
|
||||
}
|
||||
if (request.input('search')) {
|
||||
// users = users.whereRaw('name like %?%', [request.input('search')])
|
||||
const searchTerm = request.input('search');
|
||||
users.where('login', 'ilike', `%${searchTerm}%`);
|
||||
}
|
||||
|
||||
if (request.input('sort')) {
|
||||
type SortOrder = 'asc' | 'desc' | undefined;
|
||||
let attribute = request.input('sort');
|
||||
let sort_order: SortOrder = 'asc';
|
||||
if (request.input('sort')) {
|
||||
type SortOrder = 'asc' | 'desc' | undefined;
|
||||
let attribute = request.input('sort');
|
||||
let sort_order: SortOrder = 'asc';
|
||||
|
||||
// if (strncmp($attribute, '-', 1) === 0) {
|
||||
if (attribute.substr(0, 1) == '-') {
|
||||
sort_order = 'desc';
|
||||
// attribute = substr(attribute, 1);
|
||||
attribute = attribute.substr(1);
|
||||
}
|
||||
// $users->orderBy($attribute, $sort_order);
|
||||
users.orderBy(attribute, sort_order);
|
||||
} else {
|
||||
// users.orderBy('created_at', 'desc');
|
||||
users.orderBy('id', 'asc');
|
||||
}
|
||||
// if (strncmp($attribute, '-', 1) === 0) {
|
||||
if (attribute.substr(0, 1) == '-') {
|
||||
sort_order = 'desc';
|
||||
// attribute = substr(attribute, 1);
|
||||
attribute = attribute.substr(1);
|
||||
}
|
||||
// $users->orderBy($attribute, $sort_order);
|
||||
users.orderBy(attribute, sort_order);
|
||||
} else {
|
||||
// users.orderBy('created_at', 'desc');
|
||||
users.orderBy('id', 'asc');
|
||||
}
|
||||
|
||||
// const users = await User.query().orderBy('login').paginate(page, limit);
|
||||
// const users = await User.query().orderBy('login').paginate(page, limit);
|
||||
|
||||
let usersResult = await users // User.query()
|
||||
// .orderBy('login')
|
||||
// .filter(qs)
|
||||
// .preload('focusInterests')
|
||||
// .preload('role')
|
||||
.paginate(page, 5);
|
||||
let usersResult = await users // User.query()
|
||||
// .orderBy('login')
|
||||
// .filter(qs)
|
||||
// .preload('focusInterests')
|
||||
// .preload('role')
|
||||
.paginate(page, 5);
|
||||
|
||||
// var test = request.all();
|
||||
// var test = request.all();
|
||||
|
||||
return inertia.render('Admin/User/Index', {
|
||||
// testing: 'this is a test',
|
||||
users: usersResult.toJSON(),
|
||||
filters: request.all(),
|
||||
can: {
|
||||
create: await auth.user?.can(['user-create']),
|
||||
edit: await auth.user?.can(['user-edit']),
|
||||
delete: await auth.user?.can(['user-delete']),
|
||||
},
|
||||
});
|
||||
}
|
||||
return inertia.render('Admin/User/Index', {
|
||||
// testing: 'this is a test',
|
||||
users: usersResult.toJSON(),
|
||||
filters: request.all(),
|
||||
can: {
|
||||
create: await auth.user?.can(['user-create']),
|
||||
edit: await auth.user?.can(['user-edit']),
|
||||
delete: await auth.user?.can(['user-delete']),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
// let rolesPluck = {};
|
||||
// (await Role.query().select('id', 'name')).forEach((user) => {
|
||||
// rolesPluck[user.id] = user.name;
|
||||
// });
|
||||
const roles = await Role.query().select('id', 'name').pluck('name', 'id');
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
// let rolesPluck = {};
|
||||
// (await Role.query().select('id', 'name')).forEach((user) => {
|
||||
// rolesPluck[user.id] = user.name;
|
||||
// });
|
||||
const roles = await Role.query().select('id', 'name').pluck('name', 'id');
|
||||
|
||||
return inertia.render('Admin/User/Create', {
|
||||
roles: roles,
|
||||
});
|
||||
}
|
||||
return inertia.render('Admin/User/Create', {
|
||||
roles: roles,
|
||||
});
|
||||
}
|
||||
|
||||
public async store({ request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator CreateUser
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
await request.validate(CreateUserValidator);
|
||||
// console.log({ payload });
|
||||
} catch (error) {
|
||||
// Step 3 - Handle errors
|
||||
// return response.badRequest(error.messages);
|
||||
throw error;
|
||||
}
|
||||
const input = request.only(['login', 'email', 'password']);
|
||||
const user = await User.create(input);
|
||||
if (request.input('roles')) {
|
||||
const roles: Array<number> = request.input('roles');
|
||||
await user.related('roles').attach(roles);
|
||||
}
|
||||
public async store({ request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator CreateUser
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
await request.validate(CreateUserValidator);
|
||||
// console.log({ payload });
|
||||
} catch (error) {
|
||||
// Step 3 - Handle errors
|
||||
// return response.badRequest(error.messages);
|
||||
throw error;
|
||||
}
|
||||
const input = request.only(['login', 'email', 'password']);
|
||||
const user = await User.create(input);
|
||||
if (request.input('roles')) {
|
||||
const roles: Array<number> = request.input('roles');
|
||||
await user.related('roles').attach(roles);
|
||||
}
|
||||
|
||||
session.flash('message', 'User has been created successfully');
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
session.flash('message', 'User has been created successfully');
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
|
||||
public async show({ request, inertia }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
public async show({ request, inertia }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
const roles = await Role.query().pluck('name', 'id');
|
||||
// const userHasRoles = user.roles;
|
||||
const userRoles = await user.related('roles').query().orderBy('name').pluck('id');
|
||||
const roles = await Role.query().pluck('name', 'id');
|
||||
// const userHasRoles = user.roles;
|
||||
const userRoles = await user.related('roles').query().orderBy('name').pluck('id');
|
||||
|
||||
return inertia.render('Admin/User/Show', {
|
||||
roles: roles,
|
||||
user: user,
|
||||
userHasRoles: userRoles,
|
||||
});
|
||||
}
|
||||
return inertia.render('Admin/User/Show', {
|
||||
roles: roles,
|
||||
user: user,
|
||||
userHasRoles: userRoles,
|
||||
});
|
||||
}
|
||||
|
||||
public async edit({ request, inertia }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
public async edit({ request, inertia }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
const roles = await Role.query().pluck('name', 'id');
|
||||
// const userHasRoles = user.roles;
|
||||
const userHasRoles = await user.related('roles').query().orderBy('name').pluck('id');
|
||||
// let test = Object.keys(userHasRoles).map((key) => userHasRoles[key]);
|
||||
return inertia.render('Admin/User/Edit', {
|
||||
roles: roles,
|
||||
user: user,
|
||||
userHasRoles: Object.keys(userHasRoles).map((key) => userHasRoles[key]), //convert object to array with role ids
|
||||
});
|
||||
}
|
||||
const roles = await Role.query().pluck('name', 'id');
|
||||
// const userHasRoles = user.roles;
|
||||
const userHasRoles = await user.related('roles').query().orderBy('name').pluck('id');
|
||||
// let test = Object.keys(userHasRoles).map((key) => userHasRoles[key]);
|
||||
return inertia.render('Admin/User/Edit', {
|
||||
roles: roles,
|
||||
user: user,
|
||||
userHasRoles: Object.keys(userHasRoles).map((key) => userHasRoles[key]), //convert object to array with role ids
|
||||
});
|
||||
}
|
||||
|
||||
public async update({ request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator UpdateUser
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
public async update({ request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator UpdateUser
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
// validate update form
|
||||
await request.validate(UpdateUserValidator);
|
||||
// validate update form
|
||||
await request.validate(UpdateUserValidator);
|
||||
|
||||
// password is optional
|
||||
let input;
|
||||
if (request.input('password')) {
|
||||
input = request.only(['login', 'email', 'password']);
|
||||
} else {
|
||||
input = request.only(['login', 'email']);
|
||||
}
|
||||
await user.merge(input).save();
|
||||
// await user.save();
|
||||
// password is optional
|
||||
let input;
|
||||
if (request.input('password')) {
|
||||
input = request.only(['login', 'email', 'password']);
|
||||
} else {
|
||||
input = request.only(['login', 'email']);
|
||||
}
|
||||
await user.merge(input).save();
|
||||
// await user.save();
|
||||
|
||||
if (request.input('roles')) {
|
||||
const roles: Array<number> = request.input('roles');
|
||||
await user.related('roles').sync(roles);
|
||||
}
|
||||
if (request.input('roles')) {
|
||||
const roles: Array<number> = request.input('roles');
|
||||
await user.related('roles').sync(roles);
|
||||
}
|
||||
|
||||
session.flash('message', 'User has been updated successfully');
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
session.flash('message', 'User has been updated successfully');
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
|
||||
public async destroy({ request, response, session }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.findOrFail(id);
|
||||
await user.delete();
|
||||
public async destroy({ request, response, session }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.findOrFail(id);
|
||||
await user.delete();
|
||||
|
||||
session.flash('message', `User ${user.login} has been deleted.`);
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
session.flash('message', `User ${user.login} has been deleted.`);
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the user a form to change their personal information & password.
|
||||
*
|
||||
* @return — \Inertia\Response
|
||||
*/
|
||||
public accountInfo({ inertia, auth }: HttpContextContract): RenderResponse {
|
||||
const user = auth.user;
|
||||
// const id = request.param('id');
|
||||
// const user = await User.query().where('id', id).firstOrFail();
|
||||
/**
|
||||
* Show the user a form to change their personal information & password.
|
||||
*
|
||||
* @return — \Inertia\Response
|
||||
*/
|
||||
public accountInfo({ inertia, auth }: HttpContextContract): RenderResponse {
|
||||
const user = auth.user;
|
||||
// const id = request.param('id');
|
||||
// const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
return inertia.render('Admin/User/AccountInfo', {
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
return inertia.render('Admin/User/AccountInfo', {
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the modified personal information for a user.
|
||||
*
|
||||
* @param HttpContextContract ctx
|
||||
* @return : RedirectContract
|
||||
*/
|
||||
public async accountInfoStore({ request, response, auth, session }: HttpContextContract) {
|
||||
// validate update form
|
||||
await request.validate(UpdateUserValidator);
|
||||
/**
|
||||
* Save the modified personal information for a user.
|
||||
*
|
||||
* @param HttpContextContract ctx
|
||||
* @return : RedirectContract
|
||||
*/
|
||||
public async accountInfoStore({ request, response, auth, session }: HttpContextContract) {
|
||||
// validate update form
|
||||
await request.validate(UpdateUserValidator);
|
||||
|
||||
const payload = request.only(['login', 'email']);
|
||||
auth.user?.merge(payload);
|
||||
const user = await auth.user?.save();
|
||||
// $user = \Auth::user()->update($request->except(['_token']));
|
||||
let message;
|
||||
if (user) {
|
||||
message = 'Account updated successfully.';
|
||||
} else {
|
||||
message = 'Error while saving. Please try again.';
|
||||
}
|
||||
const payload = request.only(['login', 'email']);
|
||||
auth.user?.merge(payload);
|
||||
const user = await auth.user?.save();
|
||||
// $user = \Auth::user()->update($request->except(['_token']));
|
||||
let message;
|
||||
if (user) {
|
||||
message = 'Account updated successfully.';
|
||||
} else {
|
||||
message = 'Error while saving. Please try again.';
|
||||
}
|
||||
|
||||
session.flash(message);
|
||||
return response.redirect().toRoute('admin.account.info');
|
||||
//->with('message', __($message));
|
||||
}
|
||||
session.flash(message);
|
||||
return response.redirect().toRoute('admin.account.info');
|
||||
//->with('message', __($message));
|
||||
}
|
||||
|
||||
// private async syncRoles(userId: number, roleIds: Array<number>) {
|
||||
// const user = await User.findOrFail(userId)
|
||||
// // const roles: Role[] = await Role.query().whereIn('id', roleIds);
|
||||
|
||||
// // await user.roles().sync(roles.rows.map(role => role.id))
|
||||
// await user.related("roles").sync(roleIds);
|
||||
|
||||
// return user
|
||||
// }
|
||||
}
|
||||
|
|
|
@ -25,10 +25,8 @@ export default class AuthorsController {
|
|||
if (request.input('filter')) {
|
||||
// users = users.whereRaw('name like %?%', [request.input('search')])
|
||||
const searchTerm = request.input('filter');
|
||||
authors
|
||||
.whereILike('first_name', `%${searchTerm}%`)
|
||||
.orWhereILike('last_name', `%${searchTerm}%`);
|
||||
// .orWhere('email', 'like', `%${searchTerm}%`);
|
||||
authors.whereILike('first_name', `%${searchTerm}%`).orWhereILike('last_name', `%${searchTerm}%`);
|
||||
// .orWhere('email', 'like', `%${searchTerm}%`);
|
||||
}
|
||||
|
||||
let persons = await authors;
|
||||
|
|
|
@ -4,20 +4,12 @@ import Dataset from 'App/Models/Dataset';
|
|||
|
||||
// node ace make:controller Author
|
||||
export default class DatasetController {
|
||||
public async index({}: HttpContextContract) {
|
||||
// select * from gba.persons
|
||||
// where exists (select * from gba.documents inner join gba.link_documents_persons on "documents"."id" = "link_documents_persons"."document_id"
|
||||
// where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
|
||||
const datasets = await Dataset.query().where('server_state', 'published').orWhere('server_state', 'deleted');
|
||||
|
||||
public async index({}: HttpContextContract) {
|
||||
// select * from gba.persons
|
||||
// where exists (select * from gba.documents inner join gba.link_documents_persons on "documents"."id" = "link_documents_persons"."document_id"
|
||||
// where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
|
||||
const datasets = await Dataset
|
||||
.query()
|
||||
.where('server_state', 'published')
|
||||
.orWhere('server_state', 'deleted');
|
||||
|
||||
|
||||
|
||||
|
||||
return datasets;
|
||||
}
|
||||
|
||||
return datasets;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,38 +5,36 @@ import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
|||
import AuthValidator from 'App/Validators/AuthValidator';
|
||||
|
||||
export default class AuthController {
|
||||
// login function
|
||||
public async login({ request, response, auth, session }: HttpContextContract) {
|
||||
// console.log({
|
||||
// registerBody: request.body(),
|
||||
// });
|
||||
// login function
|
||||
public async login({ request, response, auth, session }: HttpContextContract) {
|
||||
// console.log({
|
||||
// registerBody: request.body(),
|
||||
// });
|
||||
await request.validate(AuthValidator);
|
||||
|
||||
const plainPassword = await request.input('password');
|
||||
const email = await request.input('email');
|
||||
// grab uid and password values off request body
|
||||
// const { email, password } = request.only(['email', 'password'])
|
||||
|
||||
|
||||
|
||||
try {
|
||||
// attempt to login
|
||||
await auth.use("web").attempt(email, plainPassword);
|
||||
} catch (error) {
|
||||
// if login fails, return vague form message and redirect back
|
||||
session.flash('message', 'Your username, email, or password is incorrect')
|
||||
return response.redirect().back()
|
||||
}
|
||||
const plainPassword = await request.input('password');
|
||||
const email = await request.input('email');
|
||||
// grab uid and password values off request body
|
||||
// const { email, password } = request.only(['email', 'password'])
|
||||
|
||||
// otherwise, redirect todashboard
|
||||
response.redirect('/dashboard');
|
||||
}
|
||||
try {
|
||||
// attempt to login
|
||||
await auth.use('web').attempt(email, plainPassword);
|
||||
} catch (error) {
|
||||
// if login fails, return vague form message and redirect back
|
||||
session.flash('message', 'Your username, email, or password is incorrect');
|
||||
return response.redirect().back();
|
||||
}
|
||||
|
||||
// logout function
|
||||
public async logout({ auth, response }: HttpContextContract) {
|
||||
// await auth.logout();
|
||||
await auth.use('web').logout();
|
||||
response.redirect('/app/login');
|
||||
// return response.status(200);
|
||||
}
|
||||
// otherwise, redirect todashboard
|
||||
response.redirect('/dashboard');
|
||||
}
|
||||
|
||||
// logout function
|
||||
public async logout({ auth, response }: HttpContextContract) {
|
||||
// await auth.logout();
|
||||
await auth.use('web').logout();
|
||||
response.redirect('/app/login');
|
||||
// return response.status(200);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,33 +1,22 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
// import User from 'App/Models/User';
|
||||
import User from 'App/Models/User';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
// import Role from 'App/Models/Role';
|
||||
// import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import License from 'App/Models/License';
|
||||
import Project from 'App/Models/Project';
|
||||
// import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Title from 'App/Models/Title';
|
||||
import Description from 'App/Models/Description';
|
||||
// import CreateUserValidator from 'App/Validators/CreateUserValidator';
|
||||
// import UpdateUserValidator from 'App/Validators/UpdateUserValidator';
|
||||
// import { RenderResponse } from '@ioc:EidelLev/Inertia';
|
||||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import dayjs from 'dayjs';
|
||||
// import Application from '@ioc:Adonis/Core/Application';
|
||||
|
||||
enum TitleTypes {
|
||||
Main = 'Main',
|
||||
Sub = 'Sub',
|
||||
Alternative = 'Alternative',
|
||||
Translated = 'Translated',
|
||||
Other = 'Other',
|
||||
}
|
||||
|
||||
enum DescriptionTypes {
|
||||
Abstract = 'Abstract',
|
||||
Methods = 'Methods',
|
||||
Series_information = 'Series_information',
|
||||
Technical_info = 'Technical_info',
|
||||
Translated = 'Translated',
|
||||
Other = 'Other',
|
||||
}
|
||||
import Person from 'App/Models/Person';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import { TransactionClientContract } from '@ioc:Adonis/Lucid/Database';
|
||||
import Subject from 'App/Models/Subject';
|
||||
import CreateDatasetValidator from 'App/Validators/CreateDatasetValidator';
|
||||
import { TitleTypes, DescriptionTypes } from 'Contracts/enums';
|
||||
|
||||
export default class DatasetController {
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
|
@ -190,7 +179,7 @@ export default class DatasetController {
|
|||
depth_min: schema.number.optional([rules.requiredIfExists('depth_max')]),
|
||||
depth_max: schema.number.optional([rules.requiredIfExists('depth_min')]),
|
||||
}),
|
||||
subjects: schema.array([rules.minLength(3)]).members(
|
||||
subjects: schema.array([rules.minLength(3), rules.uniqueArray('value')]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
|
@ -214,98 +203,161 @@ export default class DatasetController {
|
|||
}
|
||||
return response.redirect().back();
|
||||
}
|
||||
public async store({ request, response, session }: HttpContextContract) {
|
||||
const newDatasetSchema = schema.create({
|
||||
// first step
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
licenses: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one license for the new dataset
|
||||
rights: schema.string([rules.equalTo('true')]),
|
||||
// second step
|
||||
type: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
creating_corporation: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
titles: schema.array([rules.minLength(1)]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
type: schema.enum(Object.values(TitleTypes)),
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.minLength(2),
|
||||
rules.maxLength(255),
|
||||
rules.translatedLanguage('/language', 'type'),
|
||||
]),
|
||||
}),
|
||||
),
|
||||
descriptions: schema.array([rules.minLength(1)]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
type: schema.enum(Object.values(DescriptionTypes)),
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.minLength(2),
|
||||
rules.maxLength(255),
|
||||
rules.translatedLanguage('/language', 'type'),
|
||||
]),
|
||||
}),
|
||||
),
|
||||
authors: schema.array([rules.minLength(1)]).members(schema.object().members({ email: schema.string({ trim: true }) })),
|
||||
// third step
|
||||
project_id: schema.number.optional(),
|
||||
embargo_date: schema.date.optional({ format: 'yyyy-MM-dd' }, [rules.after(10, 'days')]),
|
||||
coverage: schema.object().members({
|
||||
x_min: schema.number(),
|
||||
x_max: schema.number(),
|
||||
y_min: schema.number(),
|
||||
y_max: schema.number(),
|
||||
elevation_absolut: schema.number.optional(),
|
||||
elevation_min: schema.number.optional([rules.requiredIfExists('elevation_max')]),
|
||||
elevation_max: schema.number.optional([rules.requiredIfExists('elevation_min')]),
|
||||
depth_absolut: schema.number.optional(),
|
||||
depth_min: schema.number.optional([rules.requiredIfExists('depth_max')]),
|
||||
depth_max: schema.number.optional([rules.requiredIfExists('depth_min')]),
|
||||
}),
|
||||
subjects: schema.array([rules.minLength(3)]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(255),
|
||||
// rules.unique({ table: 'dataset_subjects', column: 'value' }),
|
||||
]),
|
||||
// type: schema.enum(Object.values(TitleTypes)),
|
||||
language: schema.string({ trim: true }, [rules.minLength(2), rules.maxLength(255)]),
|
||||
}),
|
||||
),
|
||||
// file: schema.file({
|
||||
// size: '100mb',
|
||||
// extnames: ['jpg', 'gif', 'png'],
|
||||
// }),
|
||||
files: schema.array([rules.minLength(1)]).members(
|
||||
schema.file({
|
||||
size: '100mb',
|
||||
extnames: ['jpg', 'gif', 'png'],
|
||||
}),
|
||||
),
|
||||
// upload: schema.object().members({
|
||||
// label: schema.string({ trim: true }, [rules.maxLength(255)]),
|
||||
|
||||
// // label: schema.string({ trim: true }, [
|
||||
// // // rules.minLength(3),
|
||||
// // // rules.maxLength(255),
|
||||
// // ]),
|
||||
// }),
|
||||
});
|
||||
|
||||
// const coverImages = request.file('files');
|
||||
// node ace make:validator CreateUser
|
||||
public async store({ auth, request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator CreateDataset
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
// await request.validate(CreateUserValidator);
|
||||
await request.validate({ schema: newDatasetSchema, messages: this.messages });
|
||||
// await request.validate({ schema: newDatasetSchema, messages: this.messages });
|
||||
await request.validate(CreateDatasetValidator);
|
||||
// console.log({ payload });
|
||||
} catch (error) {
|
||||
// Step 3 - Handle errors
|
||||
// return response.badRequest(error.messages);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// const user = new User();
|
||||
// user.email = 'example@example.com';
|
||||
// user.password = 'password';
|
||||
// await user.useTransaction(trx).save();
|
||||
|
||||
let trx: TransactionClientContract | null = null;
|
||||
try {
|
||||
trx = await Database.transaction();
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
|
||||
// const dataset = await user.related('datasets').create({
|
||||
// type: request.input('type'),
|
||||
// creatingCorporation: request.input('creating_corporation'),
|
||||
// language: request.input('language'),
|
||||
// });
|
||||
|
||||
// Create a new instance of the Dataset model:
|
||||
const dataset = new Dataset();
|
||||
dataset.type = request.input('type');
|
||||
dataset.creatingCorporation = request.input('creating_corporation');
|
||||
dataset.language = request.input('language');
|
||||
dataset.embargoDate = request.input('embargo_date');
|
||||
//await dataset.related('user').associate(user); // speichert schon ab
|
||||
// Dataset.$getRelation('user').boot();
|
||||
// Dataset.$getRelation('user').setRelated(dataset, user);
|
||||
// dataset.$setRelated('user', user);
|
||||
await user.useTransaction(trx).related('datasets').save(dataset);
|
||||
|
||||
//store licenses:
|
||||
const licenses: number[] = request.input('licenses', []);
|
||||
dataset.useTransaction(trx).related('licenses').sync(licenses);
|
||||
|
||||
const authors = request.input('authors', []);
|
||||
for (const [key, person] of authors.entries()) {
|
||||
const pivotData = { role: 'author', sort_order: key + 1 };
|
||||
|
||||
if (person.id !== undefined) {
|
||||
await dataset
|
||||
.useTransaction(trx)
|
||||
.related('persons')
|
||||
.attach({
|
||||
[person.id]: {
|
||||
role: pivotData.role,
|
||||
sort_order: pivotData.sort_order,
|
||||
allow_email_contact: false,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const dataPerson = new Person();
|
||||
// use overwritten fill method
|
||||
dataPerson.fill(person);
|
||||
await dataset.useTransaction(trx).related('persons').save(dataPerson, false, {
|
||||
role: pivotData.role,
|
||||
sort_order: pivotData.sort_order,
|
||||
allow_email_contact: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const contributors = request.input('contributors', []);
|
||||
for (const [key, person] of contributors.entries()) {
|
||||
const pivotData = { role: 'contributor', sort_order: key + 1 };
|
||||
|
||||
if (person.id !== undefined) {
|
||||
await dataset
|
||||
.useTransaction(trx)
|
||||
.related('persons')
|
||||
.attach({
|
||||
[person.id]: {
|
||||
role: pivotData.role,
|
||||
sort_order: pivotData.sort_order,
|
||||
allow_email_contact: false,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const dataPerson = new Person();
|
||||
// use overwritten fill method
|
||||
dataPerson.fill(person);
|
||||
await dataset.useTransaction(trx).related('persons').save(dataPerson, false, {
|
||||
role: pivotData.role,
|
||||
sort_order: pivotData.sort_order,
|
||||
allow_email_contact: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//save main and additional titles
|
||||
const titles = request.input('titles', []);
|
||||
for (const titleData of titles) {
|
||||
const title = new Title();
|
||||
title.value = titleData.value;
|
||||
title.language = titleData.language;
|
||||
title.type = titleData.type;
|
||||
await dataset.useTransaction(trx).related('titles').save(title);
|
||||
}
|
||||
|
||||
//save abstract and additional descriptions
|
||||
const descriptions = request.input('descriptions', []);
|
||||
for (const descriptionData of descriptions) {
|
||||
// $descriptionReference = new Description($description);
|
||||
// $dataset->abstracts()->save($descriptionReference);
|
||||
const description = new Description();
|
||||
description.value = descriptionData.value;
|
||||
description.language = descriptionData.language;
|
||||
description.type = descriptionData.type;
|
||||
await dataset.useTransaction(trx).related('descriptions').save(description);
|
||||
}
|
||||
|
||||
//save keywords
|
||||
const keywords = request.input('subjects', []);
|
||||
for (const keywordData of keywords) {
|
||||
// $dataKeyword = new Subject($keyword);
|
||||
// $dataset->subjects()->save($dataKeyword);
|
||||
const keyword = await Subject.firstOrNew({ value: keywordData.value, type: keywordData.type }, keywordData);
|
||||
if (keyword.$isNew == true) {
|
||||
await dataset.useTransaction(trx).related('subjects').save(keyword);
|
||||
} else {
|
||||
await dataset.useTransaction(trx).related('subjects').attach([keyword.id]);
|
||||
}
|
||||
}
|
||||
|
||||
// Dataset.$getRelation('persons').boot();
|
||||
// Dataset.$getRelation('persons').pushRelated(dataset, person)
|
||||
// dataset.$pushRelated('persons', person);
|
||||
|
||||
await trx.commit();
|
||||
|
||||
console.log('Users and posts created successfully');
|
||||
} catch (error) {
|
||||
if (trx !== null) {
|
||||
await trx.rollback();
|
||||
}
|
||||
console.error('Failed to create dataset and related models:', error);
|
||||
|
||||
// Handle the error and exit the controller code accordingly
|
||||
// session.flash('message', 'Failed to create dataset and relaed models');
|
||||
// return response.redirect().back();
|
||||
throw error;
|
||||
}
|
||||
|
||||
// save data files:
|
||||
const coverImage = request.files('files')[0];
|
||||
if (coverImage) {
|
||||
// clientName: 'Gehaltsschema.png'
|
||||
|
@ -326,11 +378,6 @@ export default class DatasetController {
|
|||
);
|
||||
// let path = coverImage.filePath;
|
||||
}
|
||||
// const user = await User.create(input);
|
||||
// if (request.input('roles')) {
|
||||
// const roles: Array<number> = request.input('roles');
|
||||
// await user.related('roles').attach(roles);
|
||||
// }
|
||||
|
||||
session.flash('message', 'Dataset has been created successfully');
|
||||
// return response.redirect().toRoute('user.index');
|
||||
|
@ -367,6 +414,7 @@ export default class DatasetController {
|
|||
'after': `{{ field }} must be older than ${dayjs().add(10, 'day')}`,
|
||||
|
||||
'subjects.minLength': 'at least {{ options.minLength }} keywords must be defined',
|
||||
'subjects.uniqueArray': 'The {{ options.array }} array must have unique values based on the {{ options.field }} attribute.',
|
||||
'subjects.*.value.required': 'keyword value is required',
|
||||
'subjects.*.value.minLength': 'keyword value must be at least {{ options.minLength }} characters long',
|
||||
'subjects.*.type.required': 'keyword type is required',
|
||||
|
|
Loading…
Add table
editor.link_modal.header
Reference in a new issue