Skip to content

Commit

Permalink
added connection to db
Browse files Browse the repository at this point in the history
  • Loading branch information
michellelin1 committed Nov 27, 2023
1 parent 57cc996 commit 8c703e9
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
3 changes: 3 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ app.use(
}),
);

// add all routes under here
app.use(express.json()); // for req.body

app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
55 changes: 55 additions & 0 deletions common/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// toCamel, isArray, and isObject are helper functions used within utils only
const toCamel = (s) => {
return s.replace(/([-_][a-z])/g, ($1) => {
return $1.toUpperCase().replace('-', '').replace('_', '');
});
};

const isArray = (a) => {
return Array.isArray(a);
};

const isISODate = (str) => {
try {
const ISOString = str.toISOString();
if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(ISOString)) return false;
const d = new Date(ISOString);
return d.toISOString() === ISOString;
} catch (err) {
return false;
}
};

const isObject = (o) => {
return o === Object(o) && !isArray(o) && typeof o !== 'function' && !isISODate(o);
};

// Database columns are in snake case. JavaScript is suppose to be in camel case
// This function converts the keys from the sql query to camel case so it follows JavaScript conventions
const keysToCamel = (data) => {
if (isObject(data)) {
const newData = {};
Object.keys(data).forEach((key) => {
newData[toCamel(key)] = keysToCamel(data[key]);
});
return newData;
}
if (isArray(data)) {
return data.map((i) => {
return keysToCamel(i);
});
}
if (
typeof data === 'string' &&
data.length > 0 &&
data[0] === '{' &&
data[data.length - 1] === '}'
) {
let parsedList = data.replaceAll('"', '');
parsedList = parsedList.slice(1, parsedList.length - 1).split(',');
return parsedList;
}
return data;
};

module.exports = { keysToCamel };
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-prettier": "^4.0.0",
"express": "^4.17.1",
"express-promise-router": "^4.1.1",
"nodemon": "^2.0.14",
"pg": "^8.8.0",
"pg-promise": "^10.12.1",
"prettier": "^2.4.1"
},
"devDependencies": {
Expand Down
15 changes: 15 additions & 0 deletions server/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const pgp = require('pg-promise')({});
require('dotenv').config();

const db = pgp({
host: process.env.AWS_HOST,
user: process.env.AWS_USER,
password: process.env.AWS_PASSWORD,
port: process.env.AWS_PORT,
database: process.env.AWS_DB_NAME,
ssl: {
rejectUnauthorized: false,
},
});

module.exports = { db, pgp };

0 comments on commit 8c703e9

Please sign in to comment.