node-langoose
v1.0.0
Published
Node language manager with t-function
Downloads
5
Maintainers
Readme
How to use it
To create a translatable schema, you can use localizableModel
:
server.js
import express from 'express';
import http from 'http';
import { langMongoose } from 'node-langoose';
const mongodbUrl = 'mongodb://localhost:27017/my-db';
const user = '';
const pass = '';
mongoose.connect(mongodbUrl, { user, pass }, (err) => {
mongoose.Promise = q.Promise;
const app = express();
app.use(langMongoose());
http.createServer(app).listen(3000);
});
mycollection.js:
import { locales } from 'node-langoose';
const Schema = mongoose.Schema;
const mycollection = new Schema({
translatableString: { type: Schema.Types.ObjectId, ref: 'locale' }
someObject: {
translatableObjString: { type: Schema.Types.ObjectId, ref: 'locale' }
}
});
export const MyModel = locales.localizableModel('mycollection', mycollection);
router.js:
import express from 'express';
import mongoose from 'mongoose';
import { MyModel } from './mycollection';
const router = new express.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.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));
});
When requesting GET /mycollection/IDHERE?lang=en
it will return the collection populated:
{
"translatableString": "The value for 'en' language",
"someObject": {
"translatableObjString": "Other string for 'en' language"
}
}
When requesting GET /admin/mycollection?lang=en
, the language will be ignored (as defined in router example) and it will return all languages:
{
"translatableString": {
"en": "The value for 'en' language",
"ca": "El valor traduït al 'ca'"
},
"someObject": {
"translatableObjString": {
"en": "Other string for 'en' language",
"ca": "Una altra string en 'ca'",
}
}