refactor: fix missing await and bad practices

This commit is contained in:
alok8bb 2022-07-08 11:40:55 +05:30
parent e1c79a1840
commit 899ffa1799
No known key found for this signature in database
GPG Key ID: 748A8580B906551C
5 changed files with 39 additions and 41 deletions

5
.env
View File

@ -1,5 +0,0 @@
PORT = 8080
PGUSER=alok-pg
PGHOST=localhost
PGDATABASE=okiba
PGPORT=5432

2
.gitignore vendored
View File

@ -1,5 +1,5 @@
.env
node_modules/
public/
test/
data/
.env

View File

@ -8,12 +8,7 @@ export const getAvailableWord = async (db: Pool): Promise<Word | undefined> => {
.query(Query.getAvailableWord)
.catch((err) => err);
if (data != undefined) {
let word = data.rows[0];
return word;
}
return undefined;
return data?.rows[0];
};
export const setWordTaken = async (db: Pool, id: number) => {

View File

@ -4,12 +4,13 @@ import BinRouter from "./routes/bin";
import { Client, Pool } from "pg";
import { createDataDir, errorHandler, logError, logSuccess } from "./utils";
const main = async () => {
dotenv.config();
createDataDir();
// init db
const pool = new Pool();
const client = new Client();
const pool = await new Pool();
const client = await new Client();
client
.connect()
@ -18,6 +19,7 @@ client
})
.catch((err: Error) => {
logError(`Could not connect to database! \n\n${err.message}`);
throw err;
});
// start server
@ -35,3 +37,6 @@ app.use(errorHandler);
app.listen(port, () => {
logSuccess(`Server started on port ${port}`);
});
};
main();

View File

@ -11,6 +11,9 @@ export default function BinRouter(db: Pool) {
router.post("/paste", async (req: Request, res: Response) => {
let body: string = req.body;
if (body == undefined || body == "") {
return res.status(400).json({ message: "Invalid body!" });
}
const word: Word | undefined = await getAvailableWord(db);
@ -21,8 +24,8 @@ export default function BinRouter(db: Pool) {
(err) => err
);
setWordTaken(db, word.id);
console.log(word.id);
await setWordTaken(db, word.id);
return res.status(200).json({
endpoint: word.val,
message: "Code pasted successfully!",