Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

warmUp done #238

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions nodejs/week3/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
57 changes: 57 additions & 0 deletions nodejs/week3/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import express from 'express';
import knex from 'knex';

const knexInstance = knex({
client: "mysql2",
connection: {
host: process.env.DB_HOST || "127.0.0.1",
port: process.env.DB_PORT || 33086,
user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "mysql-root-password",
database: process.env.DB_NAME || "hyf_node_week3_warmup",
multipleStatements: true,
},
});


const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());

const apiRouter = express.Router();
app.use("/api", apiRouter);

const contactsAPIRouter = express.Router();
apiRouter.use("/contacts", contactsAPIRouter);

contactsAPIRouter.get("/", async (req, res) => {
let query = knexInstance.select("*").from("contacts");

if ("sort" in req.query) {
const orderBy = req.query.sort.toString();
if (orderBy.length > 0) {
if (orderBy === "first_name ASC" || orderBy === "first_name DESC" ||
orderBy === "last_name ASC" || orderBy === "last_name DESC") {
const [column, direction] = orderBy.split(" ");
query = query.orderBy(column, direction.toUpperCase());
} else {
return res.status(400).json({ error: "Invalid sort parameter" });
}
}
}

console.log("SQL", query.toSQL().sql);

try {
const data = await query;
res.json({ data });
} catch (e) {
console.error(e);
res.status(500).json({ error: "Internal server error" });
}
});

app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Loading