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

63 lines
1.7 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 SchemaClient {
baseUrl: string
constructor({baseUrl}: ClientOptions) {
this.baseUrl = baseUrl
}
async send(schema: SchemaInterface, data: any) {
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 }
}
}