Proyectos de Subversion Moodle

Rev

Autoría | Ultima modificación | Ver Log |

{"version":3,"file":"fetch.min.js","sources":["../src/fetch.js"],"sourcesContent":["// This file is part of Moodle - http://moodle.org/\n//\n// Moodle is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Moodle is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * The core/fetch module allows you to make web service requests to the Moodle API.\n *\n * @module     core/fetch\n * @copyright  Andrew Lyons <andrew@nicols.co.uk>\n * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n * @example <caption>Perform a single GET request</caption>\n * import Fetch from 'core/fetch';\n *\n * const result = Fetch.performGet('mod_example', 'animals', { params: { type: 'mammal' } });\n *\n * result.then((response) => {\n *    // Do something with the Response object.\n * })\n * .catch((error) => {\n *     // Handle the error\n * });\n */\n\nimport * as Cfg from 'core/config';\nimport PendingPromise from './pending';\n\n/**\n * A wrapper around the Request, including a Promise that is resolved when the request is complete.\n *\n * @class RequestWrapper\n * @private\n */\nclass RequestWrapper {\n    /** @var {Request} */\n    #request = null;\n\n    /** @var {Promise} */\n    #promise = null;\n\n    /** @var {Function} */\n    #resolve = null;\n\n    /** @var {Function} */\n    #reject = null;\n\n    /**\n     * Create a new RequestWrapper.\n     *\n     * @param {Request} request The request object that is wrapped\n     */\n    constructor(request) {\n        this.#request = request;\n        this.#promise = new Promise((resolve, reject) => {\n            this.#resolve = resolve;\n            this.#reject = reject;\n        });\n    }\n\n    /**\n     * Get the wrapped Request.\n     *\n     * @returns {Request}\n     * @private\n     */\n    get request() {\n        return this.#request;\n    }\n\n    /**\n     * Get the Promise link to this request.\n     *\n     * @return {Promise}\n     * @private\n     */\n    get promise() {\n        return this.#promise;\n    }\n\n    /**\n     * Handle the response from the request.\n     *\n     * @param {Response} response\n     * @private\n     */\n    handleResponse(response) {\n        if (response.ok) {\n            this.#resolve(response);\n        } else {\n            this.#reject(response.statusText);\n        }\n    }\n}\n\n/**\n * A class to handle requests to the Moodle REST API.\n *\n * @class Fetch\n */\nexport default class Fetch {\n    /**\n     * Make a single request to the Moodle API.\n     *\n     * @param {string} component The frankenstyle component name\n     * @param {string} action The component action to perform\n     * @param {object} params\n     * @param {object} [params.params = {}] The parameters to pass to the API\n     * @param {string|Object|FormData} [params.body = null] The HTTP method to use\n     * @param {string} [params.method = \"GET\"] The HTTP method to use\n     * @returns {Promise<Response>} A promise that resolves to the Response object for the request\n     */\n    static async request(\n        component,\n        action,\n        {\n            params = {},\n            body = null,\n            method = 'GET',\n        } = {},\n    ) {\n        const pending = new PendingPromise(`Requesting ${component}/${action} with ${method}`);\n        const requestWrapper = Fetch.#getRequest(\n            Fetch.#normaliseComponent(component),\n            action,\n            { params, method, body },\n        );\n        const result = await fetch(requestWrapper.request);\n\n        pending.resolve();\n\n        requestWrapper.handleResponse(result);\n\n        return requestWrapper.promise;\n    }\n\n    /**\n     * Make a request to the Moodle API.\n     *\n     * @param {string} component The frankenstyle component name\n     * @param {string} action The component action to perform\n     * @param {object} params\n     * @param {object} [params.params = {}] The parameters to pass to the API\n     * @returns {Promise<Response>} A promise that resolves to the Response object for the request\n     */\n    static performGet(\n        component,\n        action,\n        {\n            params = {},\n        } = {},\n    ) {\n        return this.request(\n            component,\n            action,\n            { params, method: 'GET' },\n        );\n    }\n\n    /**\n     * Make a request to the Moodle API.\n     *\n     * @param {string} component The frankenstyle component name\n     * @param {string} action The component action to perform\n     * @param {object} params\n     * @param {object} [params.params = {}] The parameters to pass to the API\n     * @returns {Promise<Response>} A promise that resolves to the Response object for the request\n     */\n    static performHead(\n        component,\n        action,\n        {\n            params = {},\n        } = {},\n    ) {\n        return this.request(\n            component,\n            action,\n            { params, method: 'HEAD' },\n        );\n    }\n\n    /**\n     * Make a request to the Moodle API.\n     *\n     * @param {string} component The frankenstyle component name\n     * @param {string} action The component action to perform\n     * @param {object} params\n     * @param {string|Object|FormData} params.body The HTTP method to use\n     * @returns {Promise<Response>} A promise that resolves to the Response object for the request\n     */\n    static performPost(\n        component,\n        action,\n        {\n            body,\n        } = {},\n    ) {\n        return this.request(\n            component,\n            action,\n            { body, method: 'POST' },\n        );\n    }\n\n    /**\n     * Make a request to the Moodle API.\n     *\n     * @param {string} component The frankenstyle component name\n     * @param {string} action The component action to perform\n     * @param {object} params\n     * @param {string|Object|FormData} params.body The HTTP method to use\n     * @returns {Promise<Response>} A promise that resolves to the Response object for the request\n     */\n    static performPut(\n        component,\n        action,\n        {\n            body,\n        } = {},\n    ) {\n        return this.request(\n            component,\n            action,\n            { body, method: 'PUT' },\n        );\n    }\n\n    /**\n     * Make a PATCH request to the Moodle API.\n     *\n     * @param {string} component The frankenstyle component name\n     * @param {string} action The component action to perform\n     * @param {object} params\n     * @param {string|Object|FormData} params.body The HTTP method to use\n     * @returns {Promise<Response>} A promise that resolves to the Response object for the request\n     */\n    static performPatch(\n        component,\n        action,\n        {\n            body,\n        } = {},\n    ) {\n        return this.request(\n            component,\n            action,\n            { body, method: 'PATCH' },\n        );\n    }\n\n    /**\n     * Make a request to the Moodle API.\n     *\n     * @param {string} component The frankenstyle component name\n     * @param {string} action The component action to perform\n     * @param {object} params\n     * @param {object} [params.params = {}] The parameters to pass to the API\n     * @param {string|Object|FormData} [params.body = null] The HTTP method to use\n     * @returns {Promise<Response>} A promise that resolves to the Response object for the request\n     */\n    static performDelete(\n        component,\n        action,\n        {\n            params = {},\n            body = null,\n        } = {},\n    ) {\n        return this.request(\n            component,\n            action,\n            {\n                body,\n                params,\n                method: 'DELETE',\n            },\n        );\n    }\n\n    /**\n     * Normalise the component name to remove the core_ prefix.\n     *\n     * @param {string} component\n     * @returns {string}\n     */\n    static #normaliseComponent(component) {\n        return component.replace(/^core_/, '');\n    }\n\n    /**\n     * Get the Request for a given API request.\n     *\n     * @param {string} component The frankenstyle component name\n     * @param {string} endpoint The endpoint within the componet to call\n     * @param {object} params\n     * @param {object} [params.params = {}] The parameters to pass to the API\n     * @param {string|Object|FormData} [params.body = null] The HTTP method to use\n     * @param {string} [params.method = \"GET\"] The HTTP method to use\n     * @returns {RequestWrapper}\n     */\n    static #getRequest(\n        component,\n        endpoint,\n        {\n            params = {},\n            body = null,\n            method = 'GET',\n        }\n    ) {\n        const url = new URL(`${Cfg.apibase}/rest/v2/${component}/${endpoint}`);\n        const options = {\n            method,\n            headers: {\n                'Accept': 'application/json',\n                'Content-Type': 'application/json',\n            },\n        };\n\n        Object.entries(params).forEach(([key, value]) => {\n            url.searchParams.append(key, value);\n        });\n\n        if (body) {\n            if (body instanceof FormData) {\n                options.body = body;\n            } else if (body instanceof Object) {\n                options.body = JSON.stringify(body);\n            } else {\n                options.body = body;\n            }\n        }\n\n        return new RequestWrapper(new Request(url, options));\n    }\n}\n"],"names":["RequestWrapper","constructor","request","Promise","resolve","reject","this","promise","handleResponse","response","ok","statusText","Fetch","component","action","params","body","method","pending","PendingPromise","requestWrapper","result","fetch","replace","endpoint","url","URL","Cfg","apibase","options","headers","Object","entries","forEach","_ref2","key","value","searchParams","append","FormData","JSON","stringify","Request"],"mappings":"y/EA2CMA,eAkBFC,YAAYC,qEAhBD,mEAGA,mEAGA,kEAGD,2CAQUA,6CACA,IAAIC,SAAQ,CAACC,QAASC,8CAClBD,4CACDC,YAUnBH,2CACOI,eASPC,2CACOD,eASXE,eAAeC,UACPA,SAASC,kDACKD,wDAEDA,SAASE,mBAUbC,2BAabC,UACAC,YACAC,OACIA,OAAS,GADbC,KAEIA,KAAO,KAFXC,OAGIA,OAAS,8DACT,SAEEC,QAAU,IAAIC,sCAA6BN,sBAAaC,wBAAeG,SACvEG,4CAAiBR,MAtBVA,wBAsBUA,mCACnBA,MAvBSA,gCAuBTA,MAA0BC,WAC1BC,OACA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