-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[v4] Composition engine #404
base: v4
Are you sure you want to change the base?
Conversation
…4fire/core into bonkalol/composition-engine-v4
…position-engine-v4
{cacheKey} = r.ctx; | ||
|
||
if (cacheKey != null && !r.destroyed) { | ||
boundedRequests.set(cacheKey, r); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@kobezzza вот тут не уверен, но лучше ничего не придумал
Мне нужно собирать request которые сделал движок чтобы при вызове engine.dropCache или engine.destroy вызывать эти же методы у всех запросов которые были созданы движком. Соответственно чтобы это сделать я держу карту [cacheKey: request] в которой сохраняю созданные запросы.
Может возникнуть коллизия и тогда старый request будет заменен свежесозданным, это ок? Не создам ли я учетек памяти тут?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут проще завести локальный асинк и в момент создания каждого запроса просто регать воркер, а потом в финальном деструкторе сделать claerAll
error; | ||
|
||
try { | ||
result = await request('', {engine}).data; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Сейчас сигнатурой request не предусмотрена возможность не передавать url запроса, что в целом то логично.
Вообще движок композиций для request модуля не совсем понятно зачем может быть нужен, основные бенефиты получает провайдер с движком (понятно что там тоже request используется, но тем не менее), а request мы и так можем композировать как хотим.
const | ||
requestFilter = provider.requestFilter?.(options, params); | ||
|
||
if (requestFilter === false) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Может просто завернуть в Promise.resolve и тогда получится простая логика: есть фильтр и нет фильтра
}, reject); | ||
|
||
function boundRequest<T extends Provider | RequestResponseObject | RequestPromise>(request: T): T { | ||
if (request instanceof Provider) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут надо ввести контракт, что если есть методы dropCache или destroy, а не смотреть на инстанс реквеста
const resultPromise = (() => { | ||
if (opts?.aggregateErrors) { | ||
return Promise.allSettled(promises) | ||
.then((results) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вынеси колбек как отдельно функцию
|
||
r.destroy = (...args) => { | ||
boundedRequests.delete(cacheKey); | ||
forkedDestroy(...args); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this потерял
const response = new Response(result, { | ||
parent: options.parent, | ||
important: options.important, | ||
responseType: 'json', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А почему json , а не object?
context = params.opts.meta.provider ?? params.ctx, | ||
providerParams = context instanceof Provider ? context.params : undefined; | ||
|
||
if (context instanceof Provider && !providersWithEngine.has(context)) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Почему проверка именно на провайдера? тут мне кажется надо просто смотреть утиной типизацией наличие методов
boundedRequests = new Map<string, RequestResponseObject>(); | ||
|
||
const | ||
providersWithEngine = new WeakSet(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А это зачем?
}); | ||
|
||
engine.dropCache = (recursive) => { | ||
boundedRequests.forEach((request) => request.dropCache(recursive)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Мне не нравиться, что ты явно разделяешь сущности - запрос и провайдер. Это должно быть без разницы. Можно воспользроваться асинк: он умеет работать как с воркерами, так и с абртабл промисами и т.д.
```typescript | ||
const r = request({engine: compositionEngine([ | ||
{ | ||
request: (opts, params, {boundRequest}) => boundRequest(request('http://locahost:5555/json/1')), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А нельзя избавиться от потребности явно вызывать bound?
|
||
} | ||
|
||
const val1 = await boundRequest(new Provider1()).get().data; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот тут кейс валидный
@@ -35,6 +35,8 @@ import type { RequestEngine, RequestOptions } from 'core/request/interface'; | |||
import { availableParams, deniedProviderParams } from 'core/request/engines/provider/const'; | |||
import type { AvailableOptions, MethodsMapping, Meta } from 'core/request/engines/provider/interface'; | |||
|
|||
export * from 'core/request/engines/composition'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А зачем это?
@@ -155,6 +155,11 @@ export interface RequestResponseObject<D = unknown> { | |||
* Destroys the request context | |||
*/ | |||
destroy(): void; | |||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А зачем это?
No description provided.