Skip to content

Commit

Permalink
Clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelim01 committed Sep 13, 2024
1 parent 9e2e78e commit 1d1065b
Show file tree
Hide file tree
Showing 11 changed files with 88 additions and 71 deletions.
8 changes: 7 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
# This is a sample environment configuration file.
# Copy this file to .env and replace the placeholder values with your own.
QUESTION_DB_CLOUD_URI=<FILL-THIS-IN>
QUESTION_DB_LOCAL_URI=mongodb://question-db:27017/question
QUESTION_DB_USERNAME=user
QUESTION_DB_PASSWORD=password
QUESTION_DB_PASSWORD=password
QUESTION_CORS_ORIGIN=*
QUESTION_PORT=8081

NODE_ENV=development
8 changes: 5 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ services:
build:
context: services/question
dockerfile: Dockerfile
environment:
MONGODB_USERNAME: ${QUESTION_DB_USERNAME}
MONGODB_PASSWORD: ${QUESTION_DB_PASSWORD}
ports:
- 8081:8081
environment:
DB_CLOUD_URI: ${QUESTION_DB_CLOUD_URI}
DB_LOCAL_URI: ${QUESTION_DB_LOCAL_URI}
DB_USERNAME: ${QUESTION_DB_USERNAME}
DB_PASSWORD: ${QUESTION_DB_PASSWORD}
volumes:
- /app/node_modules
- ./services/question:/app
Expand Down
9 changes: 9 additions & 0 deletions services/question/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# This is a sample environment configuration file.
# Copy this file to .env and replace the placeholder values with your own.
DB_CLOUD_URI=<FILL-THIS-IN>
DB_LOCAL_URI=mongodb://question-db:27017/question
DB_USERNAME=user
DB_PASSWORD=password
CORS_ORIGIN=*
PORT=8081
NODE_ENV=development
10 changes: 9 additions & 1 deletion services/question/eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,13 @@ export default tseslint.config({
...tseslint.configs.stylistic,
eslintPluginPrettierRecommended,
],
rules: {},
rules: {
// https://stackoverflow.com/questions/68816664/get-rid-of-error-delete-eslint-prettier-prettier-and-allow-use-double
'prettier/prettier': [
'error',
{
'endOfLine': 'auto',
}
]
},
});
16 changes: 7 additions & 9 deletions services/question/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,23 @@ import morgan from 'morgan';
import cors from 'cors';
import router from './routes';
import questionRouter from './routes/questionRoutes';
import { syncQuestions } from './setup';
import { connectDb } from './models';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import { corsOptions } from './config';

const app: Express = express();

// Establish database connection
connectDb();
mongoose.connection.once('open', async () => await syncQuestions());

// Middleware
app.use(morgan('dev'));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(cors(corsOptions));
app.use(
cors({
origin: process.env.CORS_ORIGIN ?? true,
methods: ['GET', 'POST', 'DELETE', 'PUT', 'PATCH'],
allowedHeaders: ['Origin', 'X-Request-With', 'Content-Type', 'Accept', 'Authorization'],
}),
);

// Routes
app.use('/', router);
Expand Down
11 changes: 0 additions & 11 deletions services/question/src/config/index.ts

This file was deleted.

File renamed without changes.
20 changes: 18 additions & 2 deletions services/question/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
import app from './app';
import { PORT } from './config';
import { connectToDB, upsertManyQuestions } from './models';
import { getDemoQuestions } from './utils/data';

app.listen(PORT, () => console.log(`App is running on port ${PORT}.`));
const port = process.env.PORT || 8081;

connectToDB()
.then(async () => {
console.log('MongoDB connected successfully');
return await getDemoQuestions();
})
.then(questions => upsertManyQuestions(questions))
.then(() => {
console.log('Questions synced successfully');
app.listen(port, () => console.log(`Question service is listening on port ${port}.`));
})
.catch(error => {
console.error('Failed to start server');
console.error(error);
});
41 changes: 26 additions & 15 deletions services/question/src/models/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import mongoose from 'mongoose';
import { MONGODB_USERNAME, MONGODB_PASSWORD, MONGODB_URL, MONGODB_DATABASE } from '../config';
import { IQuestion, Question } from './questionModel';

export const connectDb = () => {
const connectionString = `${MONGODB_URL}/${MONGODB_DATABASE}`;
export async function connectToDB() {
const mongoURI = process.env.NODE_ENV === 'production' ? process.env.DB_CLOUD_URI : process.env.DB_LOCAL_URI;

mongoose
.connect(connectionString, {
authSource: 'admin',
user: MONGODB_USERNAME,
pass: MONGODB_PASSWORD,
})
.then(() => console.log('MongoDB connected successfully'))
.catch(error => {
console.error('MongoDB connection error:', error.message);
process.exit(1);
});
};
if (!mongoURI) {
throw Error('MongoDB URI not specified');
} else if (!process.env.DB_USERNAME || !process.env.DB_PASSWORD) {
throw Error('MongoDB credentials not specified');
}

await mongoose.connect(mongoURI, {
authSource: 'admin',
user: process.env.DB_USERNAME,
pass: process.env.DB_PASSWORD,
});
}

export async function upsertManyQuestions(questions: IQuestion[]) {
const ops = questions.map(item => ({
updateOne: {
filter: { id: item.id },
update: item,
upsert: true,
},
}));
await Question.bulkWrite(ops);
}
29 changes: 0 additions & 29 deletions services/question/src/setup.ts

This file was deleted.

7 changes: 7 additions & 0 deletions services/question/src/utils/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import fs from 'fs/promises';
import { IQuestion } from '../models/questionModel';

export async function getDemoQuestions(): Promise<IQuestion[]> {
const data = await fs.readFile('./src/data/questions.json', { encoding: 'utf8' });
return JSON.parse(data);
}

0 comments on commit 1d1065b

Please sign in to comment.