Last active
February 26, 2022 10:54
-
-
Save lateau/e4eb67b373b8d8fa5d04ca35578031f2 to your computer and use it in GitHub Desktop.
kriasoft/react-starter-kit with mongoosejs
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
// src/data/models/index.js | |
import mongo from '../mongo'; | |
import User from './User'; | |
import UserLogin from './UserLogin'; | |
import UserClaim from './UserClaim'; | |
import UserProfile from './UserProfile'; | |
async function sync() { | |
await mongo.disconnect(); | |
const db = await mongo.connect(); | |
const registeredModels = db.modelNames().slice(); | |
registeredModels.forEach(modelName => delete db.models[modelName]); | |
// Load models here | |
db.model('User', User); | |
db.model('UserLogin', UserLogin); | |
db.model('UserClaim', UserClaim); | |
db.model('UserProfile', UserProfile); | |
} | |
function Model(name) { | |
return mongo.db.models[name]; | |
} | |
export default { sync }; | |
export { Model }; |
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
// src/data/mongo.js | |
import Bluebird from 'bluebird'; | |
import mongoose from 'mongoose'; | |
import config from '../config'; | |
mongoose.Promise = Bluebird; | |
const mongo = { | |
db: null, | |
options: { | |
useMongoClient: true, | |
autoIndex: false, | |
}, | |
async connect() { | |
this.db = await mongoose.connect(config.databaseUrl, this.options); | |
this.db.on('error', console.error.bind(console, 'connection error:')); | |
return this.db; | |
}, | |
disconnect() { | |
return mongoose.disconnect(); | |
}, | |
}; | |
export default mongo; |
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
// src/server.js | |
// | |
// Launch the server | |
// ----------------------------------------------------------------------------- | |
const promise = models.sync().catch(err => console.error(err.stack)); | |
if (!module.hot) { | |
promise.then(() => { | |
app.listen(config.port, () => { | |
console.info(`The server is running at http://localhost:${config.port}/`); | |
}); | |
}); | |
} | |
// | |
// Hot Module Replacement | |
// ----------------------------------------------------------------------------- | |
if (module.hot) { | |
app.hot = module.hot; | |
module.hot.accept('./router'); | |
} | |
export default app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment