Skip to content

Commit

Permalink
refactor: use openapi schema for post /defaultTriggers
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucky3028 committed Sep 25, 2023
1 parent 2600f2e commit 3af5b78
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions apps/auto-run-ac-api/src/api/defaultTriggers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { defaultTriggersSchema, type Variables, type Env, defaultTriggerSchema } from '@/model';
import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import type { SharedEnv } from 'cloudflare-env';
import { zValidator } from '@hono/zod-validator';
import { defaultTriggersTable as table } from '@/db/schema';
import { z } from 'zod';
import { getUrl, nanoid } from '@/lib';
Expand Down Expand Up @@ -43,17 +42,25 @@ export const defaultTriggersApi = app
return c.jsonT({ success: true, data: response });
},
)
.post(
'/',
// @ts-ignore TS7030
// eslint-disable-next-line consistent-return
zValidator('json', defaultTriggerSchema.omit({ id: true }), (result, c) => {
if (c.req.raw.headers.get('Content-Type') !== 'application/json') {
return c.jsonT({ success: false, messages: ['Content-Type must be "application/json"'] }, 415);
}
if (!result.success) {
return c.jsonT({ success: false, messages: result.error.issues.map((i) => i.message) }, 400);
}
.openapi(
createRoute({
request: {
body: {
content: {
'application/json': {
schema: defaultTriggerSchema.omit({ id: true }),
},
},
},
},
responses: {
201: {
description: 'Trigger is created',
content: { 'application/json': { schema: z.object({ success: z.boolean(), data: defaultTriggerSchema }) } },
},
},
method: 'post',
path: '/',
}),
async (c) => {
const contents = c.req.valid('json');
Expand All @@ -68,8 +75,10 @@ export const defaultTriggersApi = app
triggerTime: new Date(2000, 4, 15, contents.time.hour, contents.time.minute),
settingsTemp: contents.ac.temp,
operationMode: contents.ac.mode,
});
})
.onConflictDoNothing();
const response = { success: true, data: { ...contents, id } };

return c.body(null, 201, { Location: `${getUrl(c.req)}/${id}` });
return c.jsonT(response, 201, { Location: `${getUrl(c.req)}/${id}` });
},
);

0 comments on commit 3af5b78

Please sign in to comment.