Created
June 13, 2018 17:02
-
-
Save Horaddrim/c42aa7834607709b04d6e876009d22b4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // database.js | |
| const MongoClient = require('mongodb').MongoClient; | |
| async function getConnection(server) { | |
| return await MongoClient.connect(server); | |
| } | |
| /** | |
| * @param {MongoClient} client - MongoClient instance! | |
| * @param {String} databaseName - The database name string | |
| * @return Database Instance :D | |
| */ | |
| async function getDatabase(client, databaseName) { | |
| return await client.db(databaseName); | |
| } | |
| module.exports = { | |
| getConnection, | |
| getDatabase, | |
| } | |
| // ai em outro arquivo js, por exemplo, um handler do Express, | |
| const client = require('./database.js'); | |
| const Express = require('express'); | |
| async function main() { | |
| const app = Express(); | |
| // Eu crio a variável db aqui fora pra poder criar um "Singleton", | |
| // Não exatamente o conceito de Singleton, mas já ajuda a não processar muita coisa | |
| // antes de chegar no seu handler de verdade | |
| // Igual eu faço com o app | |
| const db = await client.getConnection('mongodb://localhost:27017'); | |
| // Isso aqui registra um Middleware no Express, aí todas as requisições tem acesso a esse | |
| // context! | |
| // É importante também usar as Arrow Functions, porque se não ela cria um escopo próprio e buga a porra toda kkkkk | |
| app.use('*', async (req, res, next) => { | |
| const database = await db.getDatabase('exemploDeBanco'); | |
| req.context = { | |
| database, | |
| }; | |
| next(); | |
| }); | |
| // Aqui estou no mesmo arquivo, porém QUALQUER handler (essa função (req, res) => {}) | |
| // nesse servidor pode acessar o req.context já populado! | |
| // Por isso a estrelinha no Middleware aqui em cima. | |
| app.get('/users', async (req, res) => { | |
| const database = req.context.database; | |
| const results = await database.users.find({}).toArray(); | |
| res.send(results); | |
| }); | |
| app.listen(process.env.PORT, () => console.log(`Escutando na porta ${process.env.PORT}`)); | |
| } | |
| main(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment