|
| 1 | +--- |
| 2 | +title: Remapping - ElysiaJS |
| 3 | +head: |
| 4 | + - - meta |
| 5 | + - property: 'og:title' |
| 6 | + content: Remapping - ElysiaJS |
| 7 | + |
| 8 | + - - meta |
| 9 | + - name: 'description' |
| 10 | + content: Remap existing `state`, `decorate`, `model`, `derive` to prevent name collision or renaminig a property |
| 11 | + |
| 12 | + - - meta |
| 13 | + - property: 'og:description' |
| 14 | + content: Remap existing `state`, `decorate`, `model`, `derive` to prevent name collision or renaminig a property |
| 15 | +--- |
| 16 | + |
| 17 | +# Remapping |
| 18 | +As the name suggest, this allow us to remap existing `state`, `decorate`, `model`, `derive` to anything we like to prevent name collision, or just wanting to rename a property. |
| 19 | + |
| 20 | +By providing a function as a first parameters, the callback will accept current value, allowing us to remap the value to anything we like. |
| 21 | +```ts |
| 22 | +new Elysia() |
| 23 | + .state({ |
| 24 | + a: "a", |
| 25 | + b: "b" |
| 26 | + }) |
| 27 | + // Exclude b state |
| 28 | + .state(({ b, ...rest }) => rest) |
| 29 | +``` |
| 30 | + |
| 31 | +This is useful when you have to deal with a plugin that has some duplicate name, allowing you to remap the name of the plugin: |
| 32 | +```ts |
| 33 | +new Elysia() |
| 34 | + .use( |
| 35 | + plugin |
| 36 | + .decorate(({ logger, ...rest }) => ({ |
| 37 | + pluginLogger: logger, |
| 38 | + ...rest |
| 39 | + })) |
| 40 | + ) |
| 41 | +``` |
| 42 | + |
| 43 | +Remap function can be use with `state`, `decorate`, `model`, `derive` to helps you define a correct property name and preventing name collision. |
| 44 | + |
| 45 | +## Affix |
| 46 | +To provide a smoother experience, some plugins might have a lot of property value which can be overwhelming to remap one-by-one. |
| 47 | + |
| 48 | +The **Affix** function, which consists of a **prefix** and **suffix**, allows us to effortlessly remap all properties of an instance, preventing the name collision of the plugin. |
| 49 | + |
| 50 | +```ts |
| 51 | +const setup = new Elysia({ name: 'setup' }) |
| 52 | + .decorate({ |
| 53 | + argon: 'a', |
| 54 | + boron: 'b', |
| 55 | + carbon: 'c' |
| 56 | + }) |
| 57 | + |
| 58 | +const app = new Elysia() |
| 59 | + .use( |
| 60 | + setup |
| 61 | + .prefix('decorator', 'setup') |
| 62 | + ) |
| 63 | + .get('/', ({ setupCarbon }) => setupCarbon) |
| 64 | +``` |
| 65 | + |
| 66 | +By default, **affix** will handle both runtime, type-level code automatically, remapping the property to camelCase as naming convention. |
| 67 | + |
| 68 | +In some condition, you can also remap `all` property of the plugin: |
| 69 | +```ts |
| 70 | +const app = new Elysia() |
| 71 | + .use( |
| 72 | + setup |
| 73 | + .prefix('all', 'setup') |
| 74 | + ) |
| 75 | + .get('/', ({ setupCarbon }) => setupCarbon) |
| 76 | +``` |
0 commit comments