Translation.js 944 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { TranslationServiceClient } from '@google-cloud/translate';
  2. const client = new TranslationServiceClient();
  3. const translateText = async (contents=[], targetLanguageCode='zh-CN') => {
  4. if (typeof contents === 'string') {
  5. contents = [contents];
  6. }
  7. else if (!Array.isArray(contents)) {
  8. return Promise.reject(new Error('contents must be a string or an array of strings', { cause: 400 }));
  9. }
  10. if (contents.length === 0) {
  11. return Promise.resolve([]);
  12. };
  13. const projectId = 'flyzto-cloud';
  14. const location = 'global';
  15. const request = {
  16. parent: `projects/${projectId}/locations/${location}`,
  17. contents,
  18. targetLanguageCode,
  19. };
  20. return client.translateText(request)
  21. .then(([response]) => {
  22. const result = {};
  23. response.translations.forEach((translation, index) => {
  24. result[contents[index]] = translation.translatedText;
  25. });
  26. return result;
  27. });
  28. }
  29. export default translateText;