Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/stouderio/adonis-translatable

AdonisJS package to handle translations for your models.
https://github.com/stouderio/adonis-translatable

Last synced: 6 days ago
JSON representation

AdonisJS package to handle translations for your models.

Awesome Lists containing this project

README

        



@stouder-io/adonis-translatable


Translatable fields for AdonisJS models.






npm

## Installation
This package is available in the npm registry.
```
pnpm i @stouder-io/adonis-translatable
```

## Usage
After installing the package, you can now decorate your translatable fields with the `@translation` decorator.
```ts
class Post extends BaseModel {
@column()
declare id: number

@translation()
declare title: Translation

@translation()
declare body: Translation
}
```

In your migrations, the translatable fields must be of type `json`.
```ts
export default class extends BaseSchema {
protected tableName = 'posts'

async up() {
this.schema.createTable(this.tableName, (table) => {
table.increments('id')
table.json('title')
table.json('body')
})
}

async down() {
this.schema.dropTable(this.tableName)
}
}
```

When using your model, you can now access the translated fields.
```ts
const post = await Post.find(1)
post.title.get('fr')
```

You can access it and throw if it doesn't exist.
```ts
const post = await Post.find(1)
post.title.getOrFail('fr')
```

You can also set the translated fields.
```ts
const post = await Post.find(1)
post.title.set('fr', 'Mon titre')
```

Or fully replace the translations.
```ts
const post = await Post.find(1)
post.title = Translation.from({
fr: 'Mon titre',
en: 'My title',
})
```