-
Notifications
You must be signed in to change notification settings - Fork 0
/
reasons.ts
86 lines (64 loc) · 2.5 KB
/
reasons.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { OpenAPIHono } from '@hono/zod-openapi';
import { supabase } from '../libs/supabase.js';
import { zodErrorHook } from '../libs/zodError.js';
import { createReason, deleteReason, getReasonById, getReasons, updateReason } from '../routes/reasons.js';
import { checkRole } from '../utils/context.js';
import type { Variables } from '../validators/general.js';
import { Role } from '../validators/general.js';
export const reasons = new OpenAPIHono<{ Variables: Variables }>({
defaultHook: zodErrorHook,
});
reasons.openapi(getReasons, async (c) => {
const query = supabase.from('REASONS').select('*').order('id', { ascending: true });
const { data, error } = await query;
if (error) {
return c.json({ error: error.message }, 500);
}
return c.json(data, 200);
});
reasons.openapi(getReasonById, async (c) => {
const { id } = c.req.valid('param');
const { data, error } = await supabase.from('REASONS').select('*').eq('id', id).single();
if (error || !data) {
return c.json({ error: 'Reason not found' }, 404);
}
return c.json(data, 200);
});
reasons.openapi(createReason, async (c) => {
const user = c.get('user');
const roles = user.roles;
await checkRole(roles, false, [Role.ADMIN]);
const { reason } = c.req.valid('json');
const { data, error } = await supabase.from('REASONS').insert({ reason }).select().single();
if (error) {
return c.json({ error: error.message }, 500);
}
return c.json(data, 200);
});
reasons.openapi(updateReason, async (c) => {
const user = c.get('user');
const roles = user.roles;
await checkRole(roles, false, [Role.ADMIN]);
const { id } = c.req.valid('param');
const { reason } = c.req.valid('json');
const { data, error } = await supabase.from('REASONS').update({ reason }).eq('id', id).select().single();
if (error) {
return c.json({ error: error.message }, 404);
}
return c.json(data, 200);
});
reasons.openapi(deleteReason, async (c) => {
const user = c.get('user');
const roles = user.roles;
await checkRole(roles, false, [Role.ADMIN]);
const { id } = c.req.valid('param');
const { data: existingReason, error: fetchError } = await supabase.from('REASONS').select('id').eq('id', id).single();
if (fetchError || !existingReason) {
return c.json({ error: 'Reason not found' }, 404);
}
const { error: deleteError } = await supabase.from('REASONS').delete().eq('id', id);
if (deleteError) {
return c.json({ error: deleteError.message }, 500);
}
return c.json({ message: 'Reason deleted' }, 200);
});