aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/lib/jsonapi.ts
blob: 1810c0164571de61c256bd0b098e550c534a360c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import AbstractAPI, {HttpMethod, HttpMethodLower, DataType} from './abstract-api.js';
import {isObject} from "lodash";

type APIOptions = Record<string, unknown>;

// Actual JSONAPI object
class JSONAPI extends AbstractAPI
{
    constructor(version: number = 1) {
        super(`jsonapi.php/v${version}`);
    }

    encodeData(data: DataType, method: null|HttpMethod|HttpMethodLower): DataType {
        data = super.encodeData(data, method);

        if (method && ['DELETE', 'GET', 'HEAD'].includes(method)) {
            return data;
        }

        if (isObject(data) && Object.keys(data).length === 0) {
            return null;
        }

        return JSON.stringify(data);
    }

    request<T = unknown>(url: string, options: APIOptions = {}): JQuery.jqXHR<T> {
        options.contentType = 'application/vnd.api+json';
        return super.request(url, options);
    }
}

export default JSONAPI;
export const jsonapi: JSONAPI = new JSONAPI();