Skip to content

Commit

Permalink
Connect to mongoose
Browse files Browse the repository at this point in the history
  • Loading branch information
cyri113 committed May 20, 2023
1 parent 2fc14c9 commit 82bda1f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
28 changes: 20 additions & 8 deletions src/config/env.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
import Joi from "joi";
import Joi from 'joi'

const schema = Joi.object()
const schema = Joi
.object()
.keys({
PORT: Joi.number().required().default(3000),
MONGODB_HOST: Joi.string().required().example('localhost'),
MONGODB_PORT: Joi.number().required().example(27017),
MONGODB_USER: Joi.string().required().example('root'),
MONGODB_PASS: Joi.string().required().example('pass'),
MONGODB_NAME: Joi.string().optional().example('db'),
REDIS_QUEUE_HOST: Joi.string().optional().example('localhost'),
REDIS_QUEUE_PORT: Joi.number().optional().example(6379)
})
.unknown();
.unknown()

const { value: env, error } = schema
.prefs({ errors: { label: "key" } })
.validate(process.env);
const { value: env, error } = schema.prefs({ errors: { label: 'key' } }).validate(process.env)

if (error != null) {
throw new Error(`Config validation error: ${error.message}`);
throw new Error(`Config validation error: ${error.message}`)
}

export default env;
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
const MONGODB_URL = `mongodb://${env.MONGODB_USER}:${env.MONGODB_PASS}@${env.MONGODB_HOST}:${env.MONGODB_PORT}/${env.MONGODB_NAME !== undefined ? env.MONGODB_NAME : ''}`

export default {
...env,
MONGODB_URL
}
16 changes: 12 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import mongoose from "mongoose";
import app from "./app";
import { env } from "./config";

app.listen(env.PORT, () => {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.log(`⚡️[server]: Server is running at http://localhost:${env.PORT}`);
});
mongoose.set('strictQuery', true)

main().catch(err => { console.error(err) })

async function main (): Promise<void> {
await mongoose.connect(env.MONGODB_URL)
app.listen(env.PORT, () => {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.log(`⚡️[server]: Server is running at http://localhost:${env.PORT}`)
})
}

0 comments on commit 82bda1f

Please sign in to comment.