Last active
June 18, 2024 11:17
-
-
Save SuperOleg39/f2c57459f7e86f4f14d1271df0024240 to your computer and use it in GitHub Desktop.
di-example.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // общий интерфейс | |
| interface CookieService { | |
| get(key) {} | |
| set(key, value) {} | |
| } | |
| // типизированный токен - ключ для реализации интерфейса в DI | |
| const COOKIE_SERVICE = createToken<CookieService>('cookie service'); | |
| // серверная реализация | |
| class ServerCookieService implements CookieService { | |
| get(key) { /** работает с req.cookies */} | |
| set(key, value) { /** работает с req.cookies */} | |
| } | |
| // клиентская реализация | |
| class BrowserCookieService implements CookieService { | |
| get(key) { /** работает с document.cookie */} | |
| set(key, value) { /** работает с document.cookie */} | |
| } | |
| // где-то происходит регистрация подходящей реализации в DI | |
| // используем в любом компоненте | |
| const Component = () => { | |
| // одинаково работает и на сервере и на клиенте | |
| const cookieService = useDi(COOKIE_SERVICE); | |
| return <>foo cookie valu: {cookieService.get('foo')}</>; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment