Translation.js 991 B

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