import express from 'express';
import mongoose from 'mongoose';
import { createRouter } from 'i18n-mongo';
import { MyModel } from './mycollection';
const app = express();
const mw = i18nMongo({
logger: console,
email: {
transport: nodemailer.createTransport(...),
from: 'me@appfeel.com',
to: 'me@whoiam.com',
},
defaultLanguage: '--',
}, (err) => {
console.log('Available languages loaded and i18n is ready to be used');
});
app.use(mw);
const router = createRouter(new express.Router(), { auth });
app.use('/lang', router);
router.get('/mycollection', (req, res) => {
MyModel.findLocalized({}, req.lang)
.then(res.json.bind(res))
.catch(err => res.status(500).send(err));
});
router.get('/mycollection/:_id', (req, res) => {
MyModel.findLocalized({ _id: req.params._id }, req.lang)
.then(docs => ((docs && docs.length) ? res.json(doc[0]) : res.status(404).end())
.catch(err => res.status(500).send(err));
});
router.post('/mycollection', async (req, res) => {
MyModel.saveLocalized(req.body)
.then((savedDoc) => {
const uri = `/mycollection/${savedDoc._id}`;
res.setHeader('Location', uri);
res.status(201).send(uri);
})
.catch(err => res.status(500).send(err));
});
router.put('/mycollection/:_id', async (req, res) => {
MyModel.saveLocalized(req.body, req.params._id)
.then(() => res.status(204).end())
.catch(err => res.status(500).send(err));
});
router.delete('/mycollection/:_id', async (req, res) => {
MyModel.findOne({ _id: req.params._id }).exec()
then((doc) => {
if (doc) {
doc.remove();
res.status(204).end()
} else {
res.status(404).end()
}
})
.catch(err => res.status(500).send(err));
});
router.get('/admin/mycollection', async (req, res) => {
MyModel.findLocalized({}, '')
.then(res.json.bind(res))
.catch(err => res.status(500).send(err));
});