| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- import dotenv from 'dotenv';
- import { TranslationServiceClient } from '@google-cloud/translate';
- dotenv.config();
- const client = new TranslationServiceClient();
- const translateText = async (contents=[], targetLanguageCode='zh-CN') => {
- if (typeof contents === 'string') {
- contents = [contents];
- }
- else if (!Array.isArray(contents)) {
- return Promise.reject(new Error('contents must be a string or an array of strings', { cause: 400 }));
- }
- if (contents.length === 0) {
- return Promise.resolve([]);
- };
- const projectId = 'flyzto-cloud';
- const location = 'global';
- const request = {
- parent: `projects/${projectId}/locations/${location}`,
- contents,
- targetLanguageCode,
- };
- return client.translateText(request)
- .then(([response]) => {
- const result = {};
- response.translations.forEach((translation, index) => {
- result[contents[index]] = translation.translatedText;
- });
- return result;
- });
- }
- export default translateText;
|