Added settings API
This commit is contained in:
82
app/Controllers/Http/SettingsController.ts
Normal file
82
app/Controllers/Http/SettingsController.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
||||
import Employee from 'App/Models/Employee'
|
||||
import SetSettingsValidator from 'App/Validators/SetSettingsValidator'
|
||||
|
||||
type ResultSetting = {
|
||||
key: string,
|
||||
value: string
|
||||
}
|
||||
|
||||
export default class SettingsController {
|
||||
|
||||
public async list({ params, bouncer }: HttpContextContract ): Promise<ResultSetting[]> {
|
||||
const userId = params.userId
|
||||
|
||||
try {
|
||||
const user = await Employee.findOrFail(userId)
|
||||
|
||||
await bouncer.with('SettingsPolicy').authorize('do', user)
|
||||
|
||||
const result = await user.related('settings').query().select(['key', 'value'])
|
||||
|
||||
return result
|
||||
}
|
||||
catch(error) {
|
||||
return error.message
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public async get({params, bouncer}: HttpContextContract): Promise<ResultSetting | null> {
|
||||
const userId = params.userId
|
||||
const key = params.key
|
||||
|
||||
try {
|
||||
const user = await Employee.findOrFail(userId)
|
||||
|
||||
await bouncer.with('SettingsPolicy').authorize('do', user)
|
||||
|
||||
const result = user.related('settings').query().select(['key', 'value']).where('key', key).first()
|
||||
|
||||
return result
|
||||
}
|
||||
catch(error) {
|
||||
return error.message
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public async set({params, request, bouncer}: HttpContextContract): Promise<'ok'> {
|
||||
const userId = params.userId
|
||||
|
||||
try {
|
||||
const payload = await request.validate(SetSettingsValidator)
|
||||
const user = await Employee.findOrFail(userId)
|
||||
|
||||
await bouncer.with('SettingsPolicy').authorize('do', user)
|
||||
|
||||
await user.related('settings').updateOrCreateMany(payload.settings, 'key')
|
||||
|
||||
return "ok"
|
||||
}
|
||||
catch(error){
|
||||
return error.message
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public async delete({ params, bouncer }: HttpContextContract): Promise<(0 | 1)[]> {
|
||||
const userId = params.userId
|
||||
const key = params.key
|
||||
|
||||
try {
|
||||
const user = await Employee.findOrFail(userId)
|
||||
await bouncer.with('SettingsPolicy').authorize('do', user)
|
||||
|
||||
return await user.related('settings').query().where('key', key).delete()
|
||||
}
|
||||
catch(error){
|
||||
return error.message
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user