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

React2 week1 homework #315

Open
wants to merge 5 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
6 changes: 6 additions & 0 deletions 6_nodejs/week3/DmytroKhandohii/Warmup/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
DB_HOST = 127.0.0.1
DB_PORT = 3306
DB_USER = root
DB_PASSWORD = pass
DB_NAME = hyf_node_week3_warmup
PORT = 3000
Binary file added 6_nodejs/week3/DmytroKhandohii/Warmup/.gitignore
Binary file not shown.
56 changes: 56 additions & 0 deletions 6_nodejs/week3/DmytroKhandohii/Warmup/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import knexInstance from 'knex';
import 'dotenv/config';

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-pw",
database: process.env.DB_NAME || "hyf_node_week3_warmup",
multipleStatements: true,
},
});

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.select("*").from("contacts");

const {sort} = req.query;

let columnNames = Object.keys(await knex.table('contacts').columnInfo());
const sortKey = columnNames.find((u) => u === sort);

if (sortKey) {
const orderBy = req.query.sort.toString();
if (orderBy.length > 0) {
query = query.orderByRaw(orderBy);
}
} else{
return res.status(404).send(`Sort key "${sort}" doesn't exist`);
}

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