const express = require("express"); const app = express(); const sqlite3 = require("sqlite3"); const path = require("path"); const dbPath = "app/db/database.sqlite3"; app.use(express.static(path.join(__dirname, "public"))); //all app.get("/api/v1/users", (req, res) => { const db = new sqlite3.Database(dbPath); db.all("SELECT * FROM users", (err, rows) => { res.json(rows); }); db.close(); }); //user app.get("/api/v1/users/:id", (req, res) => { const db = new sqlite3.Database(dbPath); const id = req.params.id; db.get(`SELECT * FROM users WHERE id = ${id}`, (err, row) => { res.json(row); }); db.close(); }); //search app.get("/api/v1/search", (req, res) => { const db = new sqlite3.Database(dbPath); const keyword = req.query.q; db.all(`SELECT * FROM users WHERE name LIKE "%${keyword}%"`, (err, rows) => { res.json(rows); }); db.close(); }); const port = process.env.PORT || 3000; app.listen(port); console.log("port" + port);
!DOCTYPE html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>API/title> script src="js/search.js" defer>/script> script src="js/users.js" defer>/script> script src="js/index.js" defer>/script> /head> body> main> h1>API/h1> label for="search">ユーザー名検索/label> input type="text" id="search"> button id="search-btn">検索/button> table> thead> tr> th>ID/th> th>ユーザー名/th> th>プロフィール/th> th>誕生日/th> th>登録日時/th> th>更新日時/th> /tr> /thead> tbody id="users-list"> /tbody> /table> /main> /body> /html>
const indexModule = (() => { document.getElementById("search-btn").addEventListener("click", () => { return searchModule.searchUsers(); }); return usersModule.fetchAllUsers(); })()
const usersModule = (() => { const BASE_URL = "http://localhost:3000/api/v1/users"; return { fetchAllUsers: async () => { const res = await fetch(BASE_URL); const users = await res.json(); for(let i=0; i ${user.id} ${user.name} ${user.profile} ${user.date_of_birth} ${user.created_at} ${user.updated_at} ` document.getElementById("users-list").insertAdjacentHTML("beforeend", body); } } } })()
const searchModule = (() => { const BASE_URL = "http://localhost:3000/api/v1/search"; return { searchUsers: async () => { const query = document.getElementById("search").value; const res = await fetch(BASE_URL + "?q=" + query); const result = await res.json(); let body = ""; for(let i=0; i ${user.id} ${user.name} ${user.profile} ${user.date_of_birth} ${user.created_at} ${user.updated_at} ` } document.getElementById("users-list").innerHTML = body; } } })()