Cache function for google translate node

I am using google translate node for some json messages I receive from an API.
They are usually the same messages that repeats that needs the translation.
(msg.payload in -> msg.payload out).
This function can work on any other function that repeats to avoid cpu or traffic.

How would you cache these translations and bypass google translate in case the translation request already occured.

You could use flow context storage to build up a object using the input as a key and the output as the value, and then use a function to check if the key exists before making the call out to translate... of course you may have to then manage memory if you an awful lot of phrases as they will keep adding to the space but it should work fine for most use cases I would think.

That was my thought. I will check out it works.

The contrib-cache node seems to do it that way as well.

in case anyone needs this

[{"id":"36382ba1.b5d444","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"742d4b4e.101684","type":"inject","z":"36382ba1.b5d444","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"test de tradus","payloadType":"str","x":190,"y":120,"wires":[["97dc3508.481708"]]},{"id":"9453fd8f.28212","type":"inject","z":"36382ba1.b5d444","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"test tradus","payloadType":"str","x":180,"y":160,"wires":[["97dc3508.481708"]]},{"id":"2729d227.ae7abe","type":"google-translate","z":"36382ba1.b5d444","name":"","to":"en","x":520,"y":180,"wires":[["23aa9296.2c323e"]]},{"id":"97dc3508.481708","type":"function","z":"36382ba1.b5d444","name":"","func":"var traducere = flow.get(\"traducere\") || {};\nvar tradus = traducere[msg.payload];\nif(tradus){\n    msg.payload = tradus;\n    return [msg,null];\n}\nelse {\n    msg.original = msg.payload;\n    return [null,msg];\n}","outputs":2,"noerr":0,"initialize":"","finalize":"","x":360,"y":140,"wires":[["fabb6a1e.7586b8"],["2729d227.ae7abe"]]},{"id":"23aa9296.2c323e","type":"function","z":"36382ba1.b5d444","name":"","func":"var traducere = flow.get(\"traducere\") || {};\ntraducere[msg.original] = msg.payload;\nflow.set(\"traducere\",traducere);\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":680,"y":180,"wires":[["fabb6a1e.7586b8"]]},{"id":"fabb6a1e.7586b8","type":"debug","z":"36382ba1.b5d444","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":870,"y":140,"wires":[]}]
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.