|
|
|
@ -20,24 +20,45 @@ export interface SchemaInterface { |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
export class Context { |
|
|
|
|
debouncing: number | null = null |
|
|
|
|
debouncing?: number |
|
|
|
|
useMemory?: boolean |
|
|
|
|
memoryKey?: string |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
export class SchemaClient { |
|
|
|
|
baseUrl: string | null = null |
|
|
|
|
context: Context | null = null |
|
|
|
|
|
|
|
|
|
memory: Record<string, any> = {} |
|
|
|
|
|
|
|
|
|
debouncing(time: number) |
|
|
|
|
{ |
|
|
|
|
let context = this.grabContext() |
|
|
|
|
context.debouncing = time |
|
|
|
|
this.context = context |
|
|
|
|
return this |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
useMemory(key?: string) |
|
|
|
|
{ |
|
|
|
|
let context = this.grabContext() |
|
|
|
|
context.useMemory = true |
|
|
|
|
context.memoryKey = key |
|
|
|
|
return this |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
async send(schema: SchemaInterface, data: any) { |
|
|
|
|
let context = this.context |
|
|
|
|
this.context = null |
|
|
|
|
|
|
|
|
|
if (context?.useMemory) { |
|
|
|
|
let memoryKey = context?.memoryKey || schema.url |
|
|
|
|
if (typeof this.memory[memoryKey] !== 'undefined') { |
|
|
|
|
return this.memory[memoryKey] |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
console.log('context', this.context, context) |
|
|
|
|
|
|
|
|
|
let url = `${this.baseUrl}${schema.url}` |
|
|
|
|
let {url: preparedUrl, data: preparedData} = this.processAttributes(url, data) |
|
|
|
|
|
|
|
|
@ -58,7 +79,13 @@ export class SchemaClient { |
|
|
|
|
? await response.json() |
|
|
|
|
: await response.text() |
|
|
|
|
|
|
|
|
|
return {responseData: responseData, headers: response.headers} |
|
|
|
|
let result = {responseData: responseData, headers: response.headers} |
|
|
|
|
if (context?.useMemory) { |
|
|
|
|
let memoryKey = context?.memoryKey || schema.url |
|
|
|
|
this.memory[memoryKey] = result |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return result |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
private processAttributes(url: string, data: any) |
|
|
|
@ -75,6 +102,9 @@ export class SchemaClient { |
|
|
|
|
|
|
|
|
|
private grabContext(): Context |
|
|
|
|
{ |
|
|
|
|
return this.context || new Context() |
|
|
|
|
if (this.context) { |
|
|
|
|
return this.context |
|
|
|
|
} |
|
|
|
|
return this.context = new Context() |
|
|
|
|
} |
|
|
|
|
} |