Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
13 changes: 13 additions & 0 deletions prisma/migrations/20240602214206_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- CreateTable
CREATE TABLE "todos" (
"id" TEXT NOT NULL PRIMARY KEY,
"title" TEXT NOT NULL,
"done" BOOLEAN NOT NULL DEFAULT false,
"owner" TEXT NOT NULL DEFAULT 'Anonymous',
"avatar" TEXT DEFAULT 'https://abre.ai/jUTD',
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);

-- CreateIndex
CREATE UNIQUE INDEX "todos_title_key" ON "todos"("title");
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "sqlite"
12 changes: 11 additions & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,14 @@ datasource db {
url = env("DATABASE_URL")
}

// Model definitions
model Todo {
id String @id
title String @unique
done Boolean @default(false)
owner String @default("Anonymous")
avatar String? @default("https://abre.ai/jUTD")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

@@map("todos")
}
Binary file added prisma/table.sql
Binary file not shown.
2 changes: 1 addition & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Hono } from "hono";
import { cors } from "hono/cors";
import { BrowserRouter } from "routes/index";

export const App = new Hono();
export const App = new Hono({ strict: true });
App.use(cors({ origin: "*" }));

App.route("/", BrowserRouter(App));
7 changes: 0 additions & 7 deletions src/entities/index.ts

This file was deleted.

4 changes: 4 additions & 0 deletions src/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { Todo } from "@prisma/client";

export type HttpError = { message: string };
export type HttpResponse = Todo | Todo[];
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { log } from "config/logger";
import { log } from "utils/logger";
import { App } from "./app";

Bun.serve({
Expand Down
39 changes: 11 additions & 28 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,40 @@
import { isEmpty } from "radash";
import type { Hono } from "hono";
import services from "services/index";
import * as services from "services/index";

export const BrowserRouter = (Router: Hono) => {
Router.post("/", async (context) => {
const data = await context.req.json();
const response = await services.create(data);

if (response.status !== 201)
return context.json({ error: "Failed to create resource" }, 500);

return context.body(response.data, 201);
return context.json(response);
});

Router.get("/", async (context) => {
const response = await services.read();

if (isEmpty(response.data))
return context.json({ message: "No resources registered" }, 200);
const response = await services.findMany();

return context.json(response.data, 200);
return context.json(response, 200);
});

Router.get("/:id", async (context) => {
const id = context.req.param("id");
const response = await services.findOne(id);

const response = await services.readOne(id);

if (isEmpty(response.data))
return context.json({ error: "Resource not found" }, 404);

return context.json(response.data, 200);
return context.json(response);
});

Router.put("/:id", async (context) => {
const id = context.req.param("id");
const response = await services.update(id);

if (isEmpty(response.data))
return context.json({ error: "Resource not found" }, 200);
const { title, done } = await context.req.json();
const response = await services.update(id, { title, done });

return context.json(response.data, 200);
return context.json(response);
});

Router.delete("/:id", async (context) => {
const id = context.req.param("id");
const response = await services.delete(id);

if (response.status !== 200) {
return context.json({ error: "Failed to delete resource" }, 500);
}
const response = await services.destroy(id);

return context.body(response.data, 200);
return context.json(response);
});

return Router;
Expand Down
28 changes: 28 additions & 0 deletions src/services/create/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { tryit, uid } from "radash";
import { HTTPException } from "hono/http-exception";
import type { Todo } from "@prisma/client";
import { db } from "config/orm/client";
import type { HttpError, HttpResponse } from "src/interfaces/index";

export const create = async ({
title,
done,
owner,
avatar
}: Todo): Promise<HttpResponse | HttpError> => {
const [error, todo] = await tryit(() =>
db.todo.create({
data: {
id: uid(10),
title,
done,
owner,
avatar
}
})
)();

if (error) throw new HTTPException(409, { message: "Todo Already Exists" });

return todo;
};
15 changes: 15 additions & 0 deletions src/services/delete/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { HTTPException } from "hono/http-exception";
import { tryit } from "radash";
import { db } from "config/orm/client";
import type { HttpResponse, HttpError } from "src/interfaces/index";
import { findMany } from "services/read/findMany";

export const destroy = async (
id: string
): Promise<HttpResponse | HttpError> => {
const [error] = await tryit(() => db.todo.delete({ where: { id } }))();

if (error) throw new HTTPException(404, { message: "Todo Not Found" });

return findMany();
};
37 changes: 6 additions & 31 deletions src/services/index.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,7 @@
import { uid } from "radash";
import { db } from "config/orm/client";
import type { Services } from "entities/index";
import { findMany } from "./read/findMany";
import { findOne } from "./read/findOne";
import { update } from "./update";
import { create } from "./create";
import { destroy } from "./delete";

class Service implements Services {
public async create(resource: unknown) {
// Implement the create method here
return { status: 201, data: null };
}

public async read() {
// Implement the read method here
return { status: 200, data: [] };
}

public async readOne(id: string) {
// Implement the readOne method here
return { status: 200, data: {} };
}

public async update(id: string) {
// Implement the update method here
return { status: 200, data: {} };
}

public async delete(id: string) {
// Implement the delete method here
return { status: 200, data: null };
}
}

export default new Service();
export { findMany, findOne, update, create, destroy };
9 changes: 9 additions & 0 deletions src/services/read/findMany.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { tryit } from "radash";
import { db } from "config/orm/client";
import type { HttpResponse } from "src/interfaces/index";

export const findMany = async (): Promise<HttpResponse> => {
const [_, todos] = await tryit(db.todo.findMany)();

return todos ?? [];
};
18 changes: 18 additions & 0 deletions src/services/read/findOne.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { tryit } from "radash";
import { HTTPException } from "hono/http-exception";
import type { HttpResponse, HttpError } from "src/interfaces/index";
import { db } from "config/orm/client";

export const findOne = async (
id: string
): Promise<HttpResponse | HttpError> => {
const [error, todo] = await tryit(() =>
db.todo.findUniqueOrThrow({
where: { id }
})
)();

if (error) throw new HTTPException(404, { message: "Todo Not Found" });

return todo;
};
24 changes: 24 additions & 0 deletions src/services/update/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { tryit } from "radash";
import { HTTPException } from "hono/http-exception";
import type { HttpResponse, HttpError } from "src/interfaces/index";
import { db } from "config/orm/client";

type Fields = { title: string; done: boolean };

export const update = async (
id: string,
data: Fields
): Promise<HttpResponse | HttpError> => {
const [error, todo] = await tryit(() =>
db.todo.update({
where: { id },
data: {
...data
}
})
)();

if (error) throw new HTTPException(404, { message: "Todo Not Found" });

return todo;
};
2 changes: 1 addition & 1 deletion src/config/logger.ts → src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ export const log = {
chalk.underline("http://localhost:3000"),
repository:
chalk.hex("#0ba95a").bold("Repository: ") +
chalk.underline("https://github.com/username/repo")
chalk.underline("https://github.com/brittof/galxe")
}
} satisfies Logger;
6 changes: 5 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true,
"useUnknownInCatchVariables": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
Expand All @@ -22,7 +23,10 @@
"src/config/*"
],
"entities/*": [
"src/entities/*"
"src/interfaces/*"
],
"utils/*": [
"src/utils/*"
]
}
}
Expand Down