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

node-week3/Niloufar #225

Open
wants to merge 4 commits 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules
.DS_Store
.DS_Store
.env
53 changes: 53 additions & 0 deletions 6_nodejs/week3/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import knexInstance from 'knex'
const knex= knexInstance({
client: "mysql2",
connection: {
host: process.env.DB_HOST || "127.0.0.1",
port: process.env.DB_PORT || 3306,
user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "my-secret-password",
database: process.env.DB_NAME || "hyf_node_week3_warmup",
multipleStatements: true,
},
});
import 'dotenv/config'
import express from 'express'
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 = knex("contacts").select();

if ("sort" in req.query) {
const orderBy = req.query.sort.toString();
if (orderBy === "first_name"){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the input query parameter will be first_name%20ASC, meaning sort by first name ascending. so orderby check here would be
if (orderBy === "first_name ASC"){ //... }

the same for orderBy last name.

query = query.orderBy(orderBy);
}else if(orderBy === "last_name"){
query = query.orderBy(orderBy , "desc");
}else{
res.send("invalid sort")
}
}

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤩 debug statement!! Thank you!!.. normally when we are done debugging we remove them in order not to pollute the server output


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