Skip to content

Commit 4c360f4

Browse files
committed
Initial commit
0 parents  commit 4c360f4

10 files changed

Lines changed: 947 additions & 0 deletions

File tree

.gitignore

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
2+
3+
# Logs
4+
5+
logs
6+
_.log
7+
npm-debug.log_
8+
yarn-debug.log*
9+
yarn-error.log*
10+
lerna-debug.log*
11+
.pnpm-debug.log*
12+
13+
# Caches
14+
15+
.cache
16+
17+
# Diagnostic reports (https://nodejs.org/api/report.html)
18+
19+
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
20+
21+
# Runtime data
22+
23+
pids
24+
_.pid
25+
_.seed
26+
*.pid.lock
27+
28+
# Directory for instrumented libs generated by jscoverage/JSCover
29+
30+
lib-cov
31+
32+
# Coverage directory used by tools like istanbul
33+
34+
coverage
35+
*.lcov
36+
37+
# nyc test coverage
38+
39+
.nyc_output
40+
41+
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
42+
43+
.grunt
44+
45+
# Bower dependency directory (https://bower.io/)
46+
47+
bower_components
48+
49+
# node-waf configuration
50+
51+
.lock-wscript
52+
53+
# Compiled binary addons (https://nodejs.org/api/addons.html)
54+
55+
build/Release
56+
57+
# Dependency directories
58+
59+
node_modules/
60+
jspm_packages/
61+
62+
# Snowpack dependency directory (https://snowpack.dev/)
63+
64+
web_modules/
65+
66+
# TypeScript cache
67+
68+
*.tsbuildinfo
69+
70+
# Optional npm cache directory
71+
72+
.npm
73+
74+
# Optional eslint cache
75+
76+
.eslintcache
77+
78+
# Optional stylelint cache
79+
80+
.stylelintcache
81+
82+
# Microbundle cache
83+
84+
.rpt2_cache/
85+
.rts2_cache_cjs/
86+
.rts2_cache_es/
87+
.rts2_cache_umd/
88+
89+
# Optional REPL history
90+
91+
.node_repl_history
92+
93+
# Output of 'npm pack'
94+
95+
*.tgz
96+
97+
# Yarn Integrity file
98+
99+
.yarn-integrity
100+
101+
# dotenv environment variable files
102+
103+
.env
104+
.env.development.local
105+
.env.test.local
106+
.env.production.local
107+
.env.local
108+
109+
# parcel-bundler cache (https://parceljs.org/)
110+
111+
.parcel-cache
112+
113+
# Next.js build output
114+
115+
.next
116+
out
117+
118+
# Nuxt.js build / generate output
119+
120+
.nuxt
121+
dist
122+
123+
# Gatsby files
124+
125+
# Comment in the public line in if your project uses Gatsby and not Next.js
126+
127+
# https://nextjs.org/blog/next-9-1#public-directory-support
128+
129+
# public
130+
131+
# vuepress build output
132+
133+
.vuepress/dist
134+
135+
# vuepress v2.x temp and cache directory
136+
137+
.temp
138+
139+
# Docusaurus cache and generated files
140+
141+
.docusaurus
142+
143+
# Serverless directories
144+
145+
.serverless/
146+
147+
# FuseBox cache
148+
149+
.fusebox/
150+
151+
# DynamoDB Local files
152+
153+
.dynamodb/
154+
155+
# TernJS port file
156+
157+
.tern-port
158+
159+
# Stores VSCode versions used for testing VSCode extensions
160+
161+
.vscode-test
162+
163+
# yarn v2
164+
165+
.yarn/cache
166+
.yarn/unplugged
167+
.yarn/build-state.yml
168+
.yarn/install-state.gz
169+
.pnp.*
170+
171+
# IntelliJ based IDEs
172+
.idea
173+
174+
# Finder (MacOS) folder config
175+
.DS_Store

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# simple-api
2+
3+
To install dependencies:
4+
5+
```bash
6+
bun install
7+
```
8+
9+
To run:
10+
11+
```bash
12+
bun run src/app.ts
13+
```
14+
15+
This project was created using `bun init` in bun v1.2.2. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

bun.lock

Lines changed: 541 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

database.sqlite

16 KB
Binary file not shown.

package.json

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"name": "simple-api",
3+
"author": "Max Base",
4+
"module": "src/app.ts",
5+
"type": "module",
6+
"scripts": {
7+
"dev": "bun run src/server.ts",
8+
"build": "bun run tsc",
9+
"start": "bun run dist/server.js"
10+
},
11+
"devDependencies": {
12+
"@types/bun": "latest",
13+
"@types/express": "^5.0.0",
14+
"nodemon": "^3.1.9",
15+
"ts-node": "^10.9.2"
16+
},
17+
"peerDependencies": {
18+
"typescript": "^5.7.3"
19+
},
20+
"dependencies": {
21+
"dotenv": "^16.4.7",
22+
"express": "^4.21.2",
23+
"sqlite3": "^5.1.7"
24+
}
25+
}

src/app.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import express from "express";
2+
import type { Application } from "express";
3+
import userRoutes from "./routes/userRoutes";
4+
5+
const app: Application = express();
6+
app.use(express.json());
7+
app.use("/users", userRoutes);
8+
9+
export default app;

src/db/database.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import sqlite3 from "sqlite3";
2+
3+
export interface User {
4+
id: number;
5+
name: string;
6+
email: string;
7+
}
8+
9+
const db = new sqlite3.Database("database.sqlite");
10+
11+
db.serialize(() => {
12+
db.run(`
13+
CREATE TABLE IF NOT EXISTS users (
14+
id INTEGER PRIMARY KEY AUTOINCREMENT,
15+
name TEXT NOT NULL,
16+
email TEXT UNIQUE NOT NULL
17+
)
18+
`);
19+
});
20+
21+
export function addUser(name: string, email: string, callback: (error: Error | null) => void): void {
22+
db.run("INSERT INTO users (name, email) VALUES (?, ?)", [name, email], function (err) {
23+
callback(err);
24+
});
25+
}
26+
27+
export function getUserById(id: number, callback: (error: Error | null, user?: User) => void): void {
28+
db.get<User>("SELECT * FROM users WHERE id = ?", [id], (err, row) => {
29+
callback(err, row ?? undefined);
30+
});
31+
}
32+
33+
export function getUsers(callback: (error: Error | null, users?: User[]) => void): void {
34+
db.all<User>("SELECT * FROM users", (err, rows) => {
35+
callback(err, rows ?? []);
36+
});
37+
}
38+
39+
export function getUserCount(callback: (error: Error | null, count?: number) => void): void {
40+
db.get<{ count: number }>("SELECT COUNT(*) AS count FROM users", (err, row) => {
41+
if (err) {
42+
callback(err);
43+
return;
44+
}
45+
callback(null, row?.count ?? 0);
46+
});
47+
}
48+
49+
export function deleteUser(id: number, callback: (error: Error | null, changes?: number) => void): void {
50+
db.run("DELETE FROM users WHERE id = ?", [id], function (err) {
51+
callback(err, this.changes ?? 0);
52+
});
53+
}
54+
55+
process.on("exit", () => db.close());

src/routes/userRoutes.ts

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import { Router } from "express";
2+
import type { Request, Response } from "express";
3+
import { getUsers, addUser, getUserById, getUserCount, deleteUser } from "../db/database";
4+
5+
const router: Router = Router();
6+
7+
router.get("/", (req: Request, res: Response): void => {
8+
getUsers((err, users) => {
9+
if (err) {
10+
res.status(500).send({ success: false, error: err.message });
11+
return;
12+
}
13+
res.json({ success: true, data: users });
14+
});
15+
});
16+
17+
router.get("/count", (req: Request, res: Response): void => {
18+
getUserCount((err, count) => {
19+
if (err) {
20+
res.status(500).send({ success: false, error: err.message });
21+
return;
22+
}
23+
res.json({ success: true, count });
24+
});
25+
});
26+
27+
router.get("/:id", (req: Request, res: Response): void => {
28+
const userId = req.params.id;
29+
30+
if (!/^\d+$/.test(userId)) {
31+
res.status(400).send({ success: false, error: "Invalid user ID. It must be a positive number." });
32+
return;
33+
}
34+
35+
getUserById(Number(userId), (err, user) => {
36+
if (err) {
37+
res.status(500).send({ success: false, error: err.message });
38+
return;
39+
}
40+
if (!user) {
41+
res.status(404).send({ success: false, error: "User not found" });
42+
return;
43+
}
44+
res.json({ success: true, data: user });
45+
});
46+
});
47+
48+
49+
router.post("/", (req: Request, res: Response): void => {
50+
const { name, email } = req.body;
51+
if (!name || !email) {
52+
res.status(400).send({ success: false, error: "Missing name or email" });
53+
return;
54+
}
55+
56+
addUser(name, email, (err) => {
57+
if (err) {
58+
if (err.message.includes("UNIQUE constraint failed")) {
59+
res.status(400).send({ success: false, error: "Email already exists" });
60+
} else {
61+
res.status(500).send({ success: false, error: err.message });
62+
}
63+
return;
64+
}
65+
res.json({ success: true, message: "User added successfully" });
66+
});
67+
});
68+
69+
router.delete("/:id", (req: Request, res: Response): void => {
70+
const userId = req.params.id;
71+
72+
if (!/^\d+$/.test(userId)) {
73+
res.status(400).send({ success: false, error: "Invalid user ID. It must be a positive number." });
74+
return;
75+
}
76+
77+
const userIdNumber: number = Number(userId);
78+
79+
deleteUser(userIdNumber, (err, changes) => {
80+
if (err) {
81+
res.status(500).send({ success: false, error: err.message });
82+
return;
83+
}
84+
if (changes === 0) {
85+
res.status(404).send({ success: false, error: "User not found or already deleted" });
86+
return;
87+
}
88+
res.json({ success: true, message: "User deleted successfully" });
89+
});
90+
});
91+
92+
export default router;

src/server.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import "dotenv/config";
2+
import app from "./app";
3+
4+
const PORT = process.env.PORT ? Number(process.env.PORT) : 3000;
5+
6+
app.listen(PORT, () => {
7+
console.log(`Server running on http://localhost:${PORT}`);
8+
});

0 commit comments

Comments
 (0)