Skip to content

Commit baafc2c

Browse files
committed
basic setup
1 parent 9fd5e3a commit baafc2c

24 files changed

Lines changed: 372 additions & 9 deletions

File tree

database-access/db-connection.js renamed to framework-and-drivers/database-access/db-connection.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const MongoClient = require("mongodb").MongoClient;
2+
const { logEvents } = require("../../middlewares/loggers/logger")
23
module.exports = {
34

45
connection: async () => {
@@ -13,6 +14,10 @@ module.exports = {
1314
await client.connect();
1415
} catch (err) {
1516
console.log("error connecting to database", err);
17+
logEvents(
18+
`${err.no}:${err.code}\t${err.syscall}\t${err.hostname}`,
19+
"mongoErrLog.log"
20+
);
1621
}
1722

1823
// Provide the name of the database and collection you want to use.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { makeDb } from '../src/data-access'
2+
import dotenv from 'dotenv'
3+
dotenv.config();
4+
5+
(async function setupDb () {
6+
console.log('Setting up database...')
7+
// database collection will automatically be created if it does not exist
8+
// indexes will only be added if they don't exist
9+
const db = await makeDb()
10+
const result = await db
11+
.collection('users')
12+
.createIndexes([
13+
{ key: { id: 1 }, name: 'userId_idx' },
14+
{ key: { email: 1 }, name: 'email_idx' },
15+
])
16+
console.log(result)
17+
console.log('Database setup complete...')
18+
process.exit()
19+
})()

database-access/index.js renamed to framework-and-drivers/database-access/index.js

File renamed without changes.

database-access/store-user.js renamed to framework-and-drivers/database-access/store-user.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ module.exports = async function makeUser({ dbConnection }) {
1414

1515
async function findAllUsers() {
1616
const db = await dbConnection()
17-
const result = await db.collection('comments').find({})
17+
const result = await db.collection('users').find({})
1818
return (await result.toArray()).map(({ _id: id, ...found }) => ({
1919
id,
2020
...found
@@ -23,7 +23,7 @@ module.exports = async function makeUser({ dbConnection }) {
2323

2424
async function findUserById() {
2525
const db = await dbConnection()
26-
const result = await db.collection('comments').find({ _id })
26+
const result = await db.collection('users').find({ _id })
2727
const found = await result.toArray()
2828
if (found.length === 0) {
2929
return null
@@ -35,7 +35,7 @@ module.exports = async function makeUser({ dbConnection }) {
3535
async function createUser({ id: _id = Id.makeId(), ...userData }) {
3636
const db = await dbConnection()
3737
const result = await db
38-
.collection('comments')
38+
.collection('users')
3939
.insertOne({ _id, ...userData })
4040
const { _id: id, ...insertedInfo } = result.ops[0]
4141
return { id, ...insertedInfo }
@@ -44,14 +44,14 @@ module.exports = async function makeUser({ dbConnection }) {
4444
async function updateUser({ id: _id, userData }) {
4545
const db = await dbConnection()
4646
const result = await db
47-
.collection('comments')
47+
.collection('users')
4848
.updateOne({ _id }, { $set: { ...userData } })
4949
return result.modifiedCount > 0 ? { id: _id, ...userData } : null
5050
}
5151

5252
async function deleteUser({ id: _id }) {
5353
const db = await dbConnection()
54-
const result = await db.collection('comments').deleteOne({ _id })
54+
const result = await db.collection('users').deleteOne({ _id })
5555
return result.deletedCount
5656
}
5757
}

index.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
const express = require('express');
44
require('dotenv').config();
55
const cors = require('cors');
6-
const { connection } = require('./database-access/db-connection.js');
6+
const { connection } = require('./framework-and-drivers/database-access/db-connection.js');
7+
const errorHandler = require('./middlewares/loggers/errorHandler.js');
8+
const userRouter = require('./routes/user.router.js');
79

810
connection().then((db) => {
911
console.log("database connected: ", db.databaseName);
@@ -22,6 +24,20 @@ app.use(express.urlencoded({extended: false}));
2224
app.use('/', (req, res) => {
2325
res.send('hello world');
2426
});
27+
app.use("/users", userRouter);
28+
29+
30+
//for no specified endpoint that is not found. this must after all the middlewares
31+
app.all("*", (req, res) => {
32+
res.status(404);
33+
if (req.accepts("html")) {
34+
res.sendFile(path.join(__dirname, "views", "404.html"));
35+
} else if (req.accepts("json")) {
36+
res.json({ msg: "404 Not Found" });
37+
} else {
38+
res.type("txt").send("404 Not Found");
39+
}
40+
});
2541

2642
app.use((req, res, next) => {
2743
const dntHeader = req.headers['dnt']; // Access DNT header (if present)
@@ -33,7 +49,7 @@ app.use((req, res, next) => {
3349
});
3450

3551

36-
52+
app.use(errorHandler);
3753

3854
app.listen(PORT, () => console.log(`Server started on port http://localhost:${PORT}`));
3955

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
module.exports = function makeExpressCallback (controller) {
2+
3+
return (req, res) => {
4+
const httpRequest = {
5+
body: req.body,
6+
query: req.query,
7+
params: req.params,
8+
ip: req.ip,
9+
method: req.method,
10+
path: req.path,
11+
headers: {
12+
'Content-Type': req.get('Content-Type'),
13+
Referer: req.get('referer'),
14+
'User-Agent': req.get('User-Agent')
15+
}
16+
}
17+
18+
controller(httpRequest)
19+
.then(httpResponse => {
20+
if (httpResponse.headers) {
21+
res.set(httpResponse.headers)
22+
}
23+
res.type('json')
24+
res.status(httpResponse.statusCode).send(httpResponse.body)
25+
})
26+
.catch(e => res.status(500).send({ error: 'An unkown error occurred.' }))
27+
}
28+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module.exports = {
2+
allowedOrigin: [
3+
"http://localhost:3001",
4+
],
5+
};
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const { allowedOrigin } = require("./allowedOrigin");
2+
3+
const corsOptions = {
4+
origin: (origin, callback) => {
5+
// no origin because of postman/thunder testers
6+
if (allowedOrigin.includes(origin) || !origin) {
7+
console.log({ original_request: origin });
8+
callback(null, true);
9+
} else {
10+
console.log("origin: ", origin);
11+
console.log(allowedOrigin.includes(origin));
12+
callback(new Error("NOT ALLOW BECAUSE OF CORS"));
13+
}
14+
},
15+
optionSuccessStatus: 200,
16+
credentials: true,
17+
};
18+
19+
module.exports = corsOptions;
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
export class UniqueConstraintError extends Error {
2+
constructor (value) {
3+
super(`${value} must be unique.`)
4+
5+
if (Error.captureStackTrace) {
6+
Error.captureStackTrace(this, UniqueConstraintError)
7+
}
8+
}
9+
}
10+
11+
export class InvalidPropertyError extends Error {
12+
constructor (msg) {
13+
super(msg)
14+
15+
if (Error.captureStackTrace) {
16+
Error.captureStackTrace(this, InvalidPropertyError)
17+
}
18+
}
19+
}
20+
21+
export class RequiredParameterError extends Error {
22+
constructor (param) {
23+
super(`${param} can not be null or undefined.`)
24+
25+
if (Error.captureStackTrace) {
26+
Error.captureStackTrace(this, RequiredParameterError)
27+
}
28+
}
29+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export default function makeHttpError ({ statusCode, errorMessage }) {
2+
return {
3+
headers: {
4+
'Content-Type': 'application/json'
5+
},
6+
statusCode,
7+
data: JSON.stringify({
8+
success: false,
9+
error: errorMessage
10+
})
11+
}
12+
}

0 commit comments

Comments
 (0)