You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
fms/api/schema-client.ts

80 lines
2.1 KiB

export enum Method {
GET = 'GET',
POST = 'POST',
PUT = 'PUT',
PATCH = 'PATCH',
}
export let hasQuery = (method: Method) => {
return Method.GET === method
}
export interface ClientOptions {
baseUrl: string
}
export interface SchemaInterface {
url: string,
method: Method
contentType: string | null
}
export class Context {
debouncing: number | null = null
}
export class SchemaClient {
baseUrl: string | null = null
context: Context | null = null
debouncing(time: number)
{
let context = this.grabContext()
context.debouncing = time
this.context = context
return this
}
async send(schema: SchemaInterface, data: any) {
let context = this.context
this.context = null
let url = `${this.baseUrl}${schema.url}`
let {url: preparedUrl, data: preparedData} = this.processAttributes(url, data)
if (hasQuery(schema.method)) {
preparedUrl += '?' + new URLSearchParams(preparedData)
}
let response = await fetch(preparedUrl, {
method: schema.method.toString(),
headers: {
...(schema.contentType ? {'Content-Type': schema.contentType} : {}),
'X-Plugin-Token': 'passw0rd'
},
body: hasQuery(schema.method) ? null : JSON.stringify(preparedData)
});
let responseData = response.headers.get('Content-Type')?.toString().includes('application/json')
? await response.json()
: await response.text()
return {responseData: responseData, headers: response.headers}
}
private processAttributes(url: string, data: any)
{
const preparedData = data
for (const key in data) {
if (url.indexOf('{' + key + '}') > -1) {
url = url.replace('{' + key + '}', preparedData[key])
delete preparedData[key]
}
}
return {url, data: preparedData }
}
private grabContext(): Context
{
return this.context || new Context()
}
}