Git Product home page Git Product logo

i18n-mongo's Introduction

i18n-mongo

This README document is under construction

License: EUPL v1.1 NPM version Downloads Build Status Coverage Status

Install me

$ npm i i18n-mongo --save

How to use it

To create a translatable schema, you can use localizableModel:

server.js

import express from 'express';
import http from 'http';
import { i18nMongo } from 'i18n-mongo';

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(i18nMongo());
    http.createServer(app).listen(3000);
});

mycollection.js:

import { localizableModel, Localized } from 'i18n-mongo';

const Schema = mongoose.Schema;
const mycollection = new Schema({
    translatableString: Localized
    someObject: {
        translatableObjString: Localized
    }
});

export const MyModel = localizableModel('mycollection', mycollection);

router.js:

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, // Optional
    email: { // Optional
        transport: nodemailer.createTransport(...),
        from: '[email protected]',
        to: '[email protected]',
    },
    defaultLanguage: '--', // Optional, strings in defaultLanguage will not be inserted
}, (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.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'",
    }
}

i18n-mongo's People

Contributors

dependabot[bot] avatar miqmago avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

i18n-mongo's Issues

Use common js

Hi... How i can use i18n-mongo in a node express app?
and require as common js modules
const {i18nMongo} = require('i18n-mongo'); -> not working !?

How to utilize i18n-mongo in nodejs express app

Hi... How i can use i18n-mongo in a node express app?

Wen i try load the module, i receive the error:

`server/node_modules/i18n-mongo/build/locales.js:562
schema.pre('remove', function (next) {
^

TypeError: schema.pre is not a function`

I try load this way:

`const mongoose = require('./mongoose'),
locales = require('../models/locales/locales.Model.Server'),
i18nMongo = require('i18n-mongo');

module.exports = function() {
// var locale = i18nMongo.localizableModel(name, schema);
var locale = i18nMongo.localizableModel(locale, locales);

return locale;

};`

Best Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.