Skip to content

Instantly share code, notes, and snippets.

@ezzabuzaid
Last active December 8, 2024 12:54
Show Gist options
  • Save ezzabuzaid/75526d624bbb9f96797f9527766de8b3 to your computer and use it in GitHub Desktop.
Save ezzabuzaid/75526d624bbb9f96797f9527766de8b3 to your computer and use it in GitHub Desktop.
january translation tables
import { Column, Entity, PrimaryColumn } from 'typeorm';
@Entity()
export class Locales {
@PrimaryColumn({ nullable: false })
code!: string;
@Column({ unique: true, nullable: false })
displayName!: string;
@Column()
enabled!: boolean;
}
import type { ObjectLiteral, SelectQueryBuilder } from 'typeorm';
import type { ExecutePipeline } from '../orm/execute';
import { Translations } from './translations';
/**
* Add i18n field to the query. The field is a json array of translations
* for the given locales, if the locales is empty or contains '*' then
* the i18n field is ignored.
*
* @example withI18n(qb, 'fr,en')
* @example withI18n(qb, ['fr', 'en'])
*
* @param qb query builder
* @param locales comma separated list of locales or array of locales
* @returns join locale table and add i18n field to the query
*/
export function withI18n<T extends SelectQueryBuilder<any>>(
qb: T,
locales?: string | string[]
) {
let localesArray: string[] = [];
if (locales) {
if (typeof locales === 'string') {
localesArray = locales.split(',');
} else if (Array.isArray(locales)) {
localesArray = locales;
}
}
const ignore = localesArray.includes('*') || localesArray.length === 0;
if (ignore) {
return qb;
}
localesArray = localesArray.map((locale) => locale.trim()); // remove whitespaces
return qb
.addSelect("'[' || GROUP_CONCAT(translations.i18n) || ']' as i18n")
.leftJoin(
Translations,
'translations',
`translations.entityId = ${qb.alias}.id AND translations.locale IN (:...locales)`,
{ locales: localesArray }
);
}
/**
* Assign i18n field to the entity
*/
export function assignI18n<T extends ObjectLiteral>(): ExecutePipeline<T> {
return (entity, raw) => {
const out = Object.assign(entity, {
i18n: raw.i18n,
});
return out;
};
}
import { Column, Entity, Index, PrimaryColumn } from 'typeorm';
@Entity()
@Index(['locale', 'entityId'], { unique: true })
export class Translations {
@PrimaryColumn()
locale!: string;
@PrimaryColumn()
entityId!: number;
@Column({ nullable: false, type: 'simple-json' })
i18n!: Record<string, string>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment