Skip to main content
Version: v3.x

Translate Content

Introduction

In this recipe, you'll learn how to translate existing content from your supergraph into another language. This is great for taking care of translations on the API-end to reach users worldwide. Your supergraph's consumers can choose which language(s) they want to return, all without worrying about various language configurations on the client-side.

Prerequisites

Before continuing, ensure you have:

NB: This API key is free for the first 500,000 characters each month.

Recipe

Step 1. Write the function

In your connector's directory, install the Google Cloud Translate package:
npm install @google-cloud/translate
In your functions.ts file, add the following:
import { v2 } from "@google-cloud/translate";

// This can also be stored as an environment variable
// in the connector's .env file.
const CLOUD_TRANSLATION_API_KEY = "your_cloud_translation_api_key";

/**
* @readonly
*/
export async function translateText(targetLanguage: string, content: string): Promise<string> {
const translate = new v2.Translate({ key: CLOUD_TRANSLATION_API_KEY });
const [translation] = await translate.translate(content, targetLanguage);
return translation;
}

Step 2. Track your function

To add your function, generate the related metadata that will link together any functions in your lambda connector's source files and your API:

ddn connector introspect <connector_name>

Then, you can generate an hml file for the function using the following command:

ddn command add <connector_name> "*"

Step 3. Create a relationship (optional)

Assuming the input argument's type matches that of a type belonging to one or more of your models, you can create a relationship to the command. This will enable you to make nested queries that will invoke your custom business logic using the value of the field from the related model!

Create a relationship in the corresponding model's HML file.

For example, if we have a Reviews model:
---
kind: Relationship
version: v1
definition:
name: translatedReview
sourceType: Reviews
target:
command:
name: TranslateText
mapping:
- source:
fieldPath:
- fieldName: text
target:
argument:
argumentName: content

Step 4. Test your function

Create a new build of your supergraph:

ddn supergraph build local

In your project's explorer, you should see the new function exposed as a type and should be able to make a query like this:

If you created a relationship, you can make a query like this, too:

Wrapping up

In this guide, you learned how to enhance your API and enrich the data it serves for its consumers by incorporating custom business logic directly into your supergraph. By leveraging lambda connectors with relationships, you can not only add custom business logic, but easily pass values to it and return this information as part of existing models.

Learn more about lambda connectors

Similar recipes

Loading...