-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Description
I am finding myself wanting to support multiple languages without the headache that usually follows. And i came up with this.
Let's say i have this table
article table
--------------
id: int pk
title: text
body: text
Now i want to add multiple languages for title and body columns. Run couple of SQL commands.
ALTER TABLE article ALTER COLUMN title TYPE jsonb USING json_build_object('en_US', title);
ALTER TABLE article ALTER COLUMN body TYPE jsonb USING json_build_object('en_US', body);
Hack to get custom type into hasura
CREATE VIEW article_custom_type AS SELECT 0 as id, '' as title, '' as body;
Function using X-Hasura-Language to specify the language
CREATE FUNCTION article_with_language(hasura_session JSON) RETURNS SETOF article_custom_type
STABLE
LANGUAGE sql
AS
$$
SELECT id, (article.title->>(hasura_session->>'x-hasura-language'))::TEXT, (article.body->>(hasura_session->>'x-hasura-language'))::TEXT
FROM article;
$$;
Go to Hasura web gui and track view article_custom_type and function article_with_language using session data.
To insert articles
mutation {
insert_article_one(object: {
body: {
en_US: "Example Body",
is_IS: "Íslenskt dæmi"
},
title: {
en_US: "Example Title",
is_IS: "Íslenskur titill"
}
}) {
id
}
}
To query
query {
article_with_language {
id
title
body
}
}
This works great. Having the query return standard types instead of json is really nice. But there are some issues with this approach.
- Every time when updating the schema for tables i will also have to update the custom view and function.
- Supporting multiple languages application wide will mean most tables will need this so alot of custom views and functions.
- The view hack for custom type is a bit ugly
If it was possible to easily "augment" specific columns like this that would be very be interesting and could probably solve other use cases as well.
Are there any standard practices for working with multiple languages in Hasura or things i'm missing that could prove useful ?