|
1 | 1 | # Service Tokens
|
| 2 | + |
| 3 | +Service tokens are unique identifiers what provides a type-safe access to a value stored in a `Conatiner`. |
| 4 | + |
| 5 | +```ts |
| 6 | +import 'reflect-metadata'; |
| 7 | +import { Container, Token } from 'typedi'; |
| 8 | + |
| 9 | +export const JWT_SECRET_TOKEN = new Token<string>('MY_SECRET'); |
| 10 | + |
| 11 | +Container.set(JWT_SECRET_TOKEN, 'wow-such-secure-much-encryption'); |
| 12 | + |
| 13 | +/** |
| 14 | + * Somewhere else in the application after the JWT_SECRET_TOKEN is |
| 15 | + * imported in can be used to request the secret from the Container. |
| 16 | + * |
| 17 | + * This value is type-safe also because the Token is typed. |
| 18 | + */ |
| 19 | +const JWT_SECRET = Container.get(JWT_SECRET_TOKEN); |
| 20 | +``` |
| 21 | + |
| 22 | +## Injecting service tokens |
| 23 | + |
| 24 | +They can be used with the `@Inject()` decorator to overwrite the inferred type of the property of argument. |
| 25 | + |
| 26 | +```ts |
| 27 | +import 'reflect-metadata'; |
| 28 | +import { Container, Token, Inject, Service } from 'typedi'; |
| 29 | + |
| 30 | +export const JWT_SECRET_TOKEN = new Token<string>('MY_SECRET'); |
| 31 | + |
| 32 | +Container.set(JWT_SECRET_TOKEN, 'wow-such-secure-much-encryption'); |
| 33 | + |
| 34 | +@Service() |
| 35 | +class Example { |
| 36 | + @Inject(JWT_SECRET_TOKEN) |
| 37 | + myProp: string; |
| 38 | +} |
| 39 | + |
| 40 | +const instance = Container.get(Example); |
| 41 | +// The instance.myProp property has the value assigned for the Token |
| 42 | +``` |
| 43 | + |
| 44 | +## Tokens with same name |
| 45 | + |
| 46 | +Two token **with the same name are different tokens**. The name is only used to help the developer identify the tokens |
| 47 | +during debugging and development. (It's included in error the messages.) |
| 48 | + |
| 49 | +```ts |
| 50 | +import 'reflect-metadata'; |
| 51 | +import { Container, Token } from 'typedi'; |
| 52 | + |
| 53 | +const tokenA = new Token('TOKEN'); |
| 54 | +const tokenB = new Token('TOKEN'); |
| 55 | + |
| 56 | +Container.set(tokenA, 'value-A'); |
| 57 | +Container.set(tokenB, 'value-B'); |
| 58 | + |
| 59 | +const tokenValueA = Container.get(tokenA); |
| 60 | +// tokenValueA is "value-A" |
| 61 | +const tokenValueB = Container.get(tokenB); |
| 62 | +// tokenValueB is "value-B" |
| 63 | + |
| 64 | +console.log(tokenValueA === tokenValueB); |
| 65 | +// returns false, as Tokens are always unique |
| 66 | +``` |
| 67 | + |
| 68 | +### Difference between Token and string identifier |
| 69 | + |
| 70 | +They both achieve the same goal, however it's recommended to use `Tokens` as they are type-safe and cannot be mistyped, |
| 71 | +while a mistyped string identifier will silently return `undefined` as value by default. |
0 commit comments