Files
test-api/src/index.ts
T

118 lines
3.0 KiB
TypeScript

import { Hono } from "hono";
import { ApiResponse } from "./modules/api_response";
import { validator } from "hono/validator";
import { postUser } from "./service/postUser";
import { isEmpty } from "./utils/is_empty";
import { getUser } from "./service/getUser";
import { bodyLimit } from "hono/body-limit";
import { getRandom } from "./service/getRandom";
const tmpApp: Hono = new Hono()
export const app = tmpApp.basePath("/test/")
// routers
app.get("/user", (c) => {
const re = getUser()
return c.json(ApiResponse.success(200, "Get user successfully", re))
})
app.post(
"/user",
validator("json", (val, c) => {
if (isEmpty(val.name, val.passwd)) {
c.status(400)
return c.json(ApiResponse.err(400, "Param is invalid"))
}
return val
}),
c => {
const re = postUser()
return c.json(ApiResponse.success(200, "Add successfully", re))
}
)
app.patch("/user",
validator("json", (val, c) => {
if (isEmpty(val.id, val.changeFields)) {
c.status(400)
return c.json(ApiResponse.err(400, "Param is invalid"))
}
return val
}),
c => {
return c.json(ApiResponse.success(200, "Change user information successfully"))
}
)
app.put("/user",
validator("json", (val, c) => {
if (isEmpty(val.id, val.changeFields)) {
c.status(400)
return c.json(ApiResponse.err(400, "Param is invalid"))
}
return val
}),
c => {
return c.json(ApiResponse.success(200, "Change user information successfully"))
}
)
app.delete("/user",
validator("json", (val, c) => {
if (isEmpty(val.id)) {
c.status(400)
return c.json(ApiResponse.err(400, "Param is invalid"))
}
return val
}),
async (c) => {
const id = await c.req.json()
return c.json(ApiResponse.success(200, `Delete user successfully by id: ${id.id}`))
}
)
app.post("/file",
bodyLimit({
maxSize: 5 * 1024 * 1024,
onError: (c) => {
return c.json(ApiResponse.err(400, "File must less than 5MB"))
}
}),
async (c) => {
const body = await c.req.parseBody()
const file = body["file"]
if (!(file instanceof File)) {
return c.json(ApiResponse.err(400, "Not file"))
}
const fileName = file.name
const fileSize = file.size
return c.json(ApiResponse.success(200, "Upload file successfully", {
fileName,
fileSize
}))
}
)
app.get("/random",
validator("query", (val, c) => {
if (isEmpty(val.typeList, val.length)) {
c.status(400)
return c.json(ApiResponse.err(400, "Param is invalid"))
}
return val
}),
c => {
return getRandom(c)
}
)
app.notFound((c) => {
console.log(`Not found [${c.req.method}]: ${c.req.path}`);
return c.json(ApiResponse.err(404, "Not Found"))
})
export default {
port: "8080",
fetch: app.fetch
}