Skip to content

Commit 933cb20

Browse files
committed
create crud api code
1 parent e7966ba commit 933cb20

File tree

7 files changed

+1321
-0
lines changed

7 files changed

+1321
-0
lines changed

.gitignore

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

db.js

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
const mysql = require("mysql2");
2+
const dotenv = require("dotenv");
3+
4+
dotenv.config();
5+
6+
const connection = mysql.createConnection({
7+
host: process.env.DB_HOST,
8+
user: process.env.DB_USER,
9+
password: process.env.DB_PASSWORD,
10+
database: process.env.DB_NAME
11+
});
12+
13+
// Connect to MySQL
14+
connection.connect((err) => {
15+
if (err) {
16+
console.error("Database connection failed:", err);
17+
return;
18+
}
19+
console.log("Connected to MySQL");
20+
21+
// Create database if not exists
22+
connection.query(
23+
`CREATE DATABASE IF NOT EXISTS ${process.env.DB_NAME}`,
24+
(err) => {
25+
if (err) {
26+
console.error("Database creation failed:", err);
27+
return;
28+
}
29+
console.log("Database ready");
30+
31+
// Connect to the newly created database
32+
const db = mysql.createConnection({
33+
host: process.env.DB_HOST,
34+
user: process.env.DB_USER,
35+
password: process.env.DB_PASSWORD,
36+
database: process.env.DB_NAME,
37+
});
38+
39+
db.connect((err) => {
40+
if (err) {
41+
console.error("Database selection failed:", err);
42+
return;
43+
}
44+
45+
// Create table if not exists
46+
db.query(
47+
`CREATE TABLE IF NOT EXISTS words (
48+
id INT AUTO_INCREMENT PRIMARY KEY,
49+
word VARCHAR(255) NOT NULL
50+
)`,
51+
(err) => {
52+
if (err) {
53+
console.error("Table creation failed:", err);
54+
return;
55+
}
56+
console.log("Table ready");
57+
}
58+
);
59+
});
60+
}
61+
);
62+
});
63+
64+
module.exports = connection;

index.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
require("dotenv").config();
2+
require("./db"); // Ensures database setup runs before starting the server
3+
4+
const express = require("express");
5+
const wordsRouter = require("./routes/words");
6+
7+
const app = express();
8+
const PORT = process.env.PORT || 3000;
9+
10+
app.use(express.json());
11+
12+
// Health Check
13+
app.get("/health", (req, res) => {
14+
res.json({ status: "healthy" });
15+
});
16+
17+
// Word Routes
18+
app.use("/api/words", wordsRouter);
19+
20+
app.listen(PORT, () => {
21+
console.log(`Server running on http://localhost:${PORT}`);
22+
});

models/wordModel.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const pool = require("../db");
2+
3+
const getAllWords = async () => {
4+
const [rows] = await pool.promise().query("SELECT * FROM words");
5+
return rows;
6+
};
7+
8+
const getWordById = async (id) => {
9+
const [rows] = await pool.promise().query("SELECT * FROM words WHERE id = ?", [id]);
10+
return rows[0];
11+
};
12+
13+
const insertWord = async (word) => {
14+
const [result] = await pool.promise().query("INSERT INTO words (word) VALUES (?)", [word]);
15+
return { id: result.insertId, word };
16+
};
17+
18+
const updateWord = async (id, word) => {
19+
await pool.promise().query("UPDATE words SET word = ? WHERE id = ?", [word, id]);
20+
return getWordById(id);
21+
};
22+
23+
const deleteWord = async (id) => {
24+
const [result] = await pool.promise().query("DELETE FROM words WHERE id = ?", [id]);
25+
return result.affectedRows > 0;
26+
};
27+
28+
module.exports = {
29+
getAllWords,
30+
getWordById,
31+
insertWord,
32+
updateWord,
33+
deleteWord
34+
};

0 commit comments

Comments
 (0)