#2 connected to mongodb

parent 98b1cb39
DB_CONN_STRING="mongodb://localhost:27017"
DB_NAME="linksDB"
LINKS_COLLECTION_NAME="links"
PORT='3000'
\ No newline at end of file
This diff is collapsed.
......@@ -10,8 +10,11 @@
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^18.15.0",
"cors": "^2.8.5",
"express": "^4.18.2"
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongodb": "^5.1.0"
},
"devDependencies": {
"@types/cors": "^2.8.13",
......
import express, {Express} from 'express';
import {linksRouter} from './routes/linksRouter';
import {linksRouter} from './routes/links.router';
import {connectToDatabase} from './services/database.service';
const app: Express = express();
app.use(express.json());
app.use('/links', linksRouter);
app.listen(3000, () => {
console.log(`Server is listening on port 3000`);
});
connectToDatabase()
.then(() => {
app.use('/links', linksRouter);
app.listen(process.env.PORT, () => {
console.log(`Server started at http://localhost:${process.env.PORT}`);
});
})
.catch((error: Error) => {
console.log('Database connection failed');
process.exit();
});
import {ObjectId} from 'mongodb';
export default class Link {
constructor(public originalUrl: string, public id?: ObjectId) {}
}
import express, {Router, Request, Response} from 'express';
import {ObjectId} from 'mongodb';
import {collections} from '../services/database.service';
import Link from '../models/links';
export const linksRouter: Router = express.Router();
linksRouter.get('/', (req: Request, res: Response) => {
try {
res.send('Hello');
} catch (error: unknown) {
const err = error as Error;
res.status(500).send(err.message);
}
});
linksRouter.post('/', async (req: Request, res: Response) => {
try {
const newLink = req.body as Link;
const result = await collections.links?.insertOne(newLink);
if (result) {
res
.status(201)
.send(`Successfully created a new link with id ${result.insertedId}`);
} else {
res.status(500).send('Failed to create a new link.');
}
} catch (err: unknown) {
const error = err as Error;
res.status(500).send(error.message);
}
});
import express, {Router, Request, Response} from 'express';
export const linksRouter: Router = express.Router();
linksRouter.get('/', (req: Request, res: Response) => {
res.send('Hello');
});
linksRouter.post('/', (req: Request, res: Response) => {
res.send('Hello');
});
import * as mongoDB from 'mongodb';
import * as dotenv from 'dotenv';
export const collections: {links?: mongoDB.Collection} = {};
export const connectToDatabase = async () => {
dotenv.config();
const client: mongoDB.MongoClient = new mongoDB.MongoClient(
process.env.DB_CONN_STRING
);
await client.connect();
const db: mongoDB.Db = client.db(process.env.DB_NAME);
const linksCollection: mongoDB.Collection = db.collection(
process.env.LINKS_COLLECTION_NAME
);
collections.links = linksCollection;
console.log('Connected to database');
};
declare global {
namespace NodeJS {
interface ProcessEnv {
PORT: string;
DB_CONN_STRING: string;
DB_NAME: string;
LINKS_COLLECTION_NAME: string;
}
}
}
export {};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment