franciscop / translate

:sa: Translate text on node.js and the browser with promises
MIT License
288 stars 44 forks source link

Feature request: modularization of engines #20

Closed euberdeveloper closed 3 years ago

euberdeveloper commented 3 years ago

Hi, I did not see the options of a modularization of engines and I think that it could be cool.

I see from the code that an engine is just a function that gets some fixed parameters (key, text, from, to) and returns the translation.

Will the possibility of adding a custom engine be ever implemented?

franciscop commented 3 years ago

Hi, I did not see the options of a modularization of engines and I think that it could be cool.

Sorry I'm not sure what you mean, the engines are modularized in the engines.js file, which contains all of the currently available the engines.

Will the possibility of adding a custom engine be ever implemented?

To add a custom engine, you can add it to engines.js following the format of the current ones and send a PR. Does that answer the question?

euberdeveloper commented 3 years ago

No, sorry, that is not what I meant. To add it to engines.js, I should directly modify the code of the module. This is not beautiful and neither good, because if someone else installs the module with npm I can not reproduce the same project.

So I meant something like adding an option in order to add a custom engine, such as translate.use('myengine', async (to, from, key) => {});.

Something like chai.use like here (https://www.chaijs.com/guide/plugins/)

franciscop commented 3 years ago

I see, what is the usecase then? If you create a custom engine, which is already most of the code to make Translate work, and then call it from your own code? Why not just create it in your code straight away? Instead of:

translate.use('myengine', async (text, to, from, key) => {});

You could just do:

const translate = async (text, to, from = 'en') => {};

That way you don't need an external library only to do that.

The reason I created Translate is so that I can easily change engines if something goes wrong with one of them (which you can keep by using the same API) and that I don't need to worry every time about re-implementing the logic (which you need to do as a custom engine).

So, what is the advantage/case of using a custom engine like this?

euberdeveloper commented 3 years ago

The advantage would be that if an engine that is not among yours stops to do it's job (maybe the key is not valid), you can fallback to another one by changing only a string.

franciscop commented 3 years ago

In that case, you are going to need to have a file for it anyway so you can do:

import translate from 'translate';

const myCustomTranslate = (str, { from, to }) => {
  ...
};

// Change the translation by swapping the next lines
export default myCustomTranslate;
// export translate;

Then you only need to change those last two lines in the project to change translations.