| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- /**
- * A basic api request service
- *
- * It will send basic http requests and returns raw results
- */
- import {AssociativeArray, HTTP_METHOD} from "~/types/data.d";
- import {$Fetch} from "nitropack";
- import {FetchOptions} from "ohmyfetch";
- class ApiRequestService {
- private readonly fetch: $Fetch
- public constructor(
- fetch: $Fetch
- ) {
- this.fetch = fetch
- }
- /**
- * Send a GET request
- *
- * @param url
- * @param query
- */
- public async get(
- url: string,
- query: AssociativeArray | null = null
- ) {
- return await this.request(HTTP_METHOD.GET, url, null, null, query)
- }
- /**
- * Send a POST request
- *
- * @param url
- * @param body
- * @param params
- * @param query
- */
- public async post(
- url: string,
- body: string | null = null,
- params: AssociativeArray | null = null,
- query: AssociativeArray | null = null
- ) {
- return await this.request(HTTP_METHOD.POST, url, body, params, query)
- }
- /**
- * Send a PUT request
- *
- * @param url
- * @param body
- * @param params
- * @param query
- */
- public async put(
- url: string,
- body: string | null = null,
- params: AssociativeArray | null = null,
- query: AssociativeArray | null = null
- ) {
- return await this.request(HTTP_METHOD.PUT, url, body, params, query)
- }
- /**
- * Send a DELETE request
- *
- * @param url
- * @param query
- */
- public async delete(
- url: string,
- query: AssociativeArray | null = null
- ) {
- return await this.request(HTTP_METHOD.DELETE, url, null, null, query)
- }
- /**
- * Send an http request
- *
- * @param method
- * @param url
- * @param body
- * @param params
- * @param query
- * @private
- */
- private async request(
- method: HTTP_METHOD,
- url: string,
- body: string | null = null,
- params: AssociativeArray | null = null,
- query: AssociativeArray | null = null
- ): Promise<Response> {
- const config: FetchOptions = { method }
- if (params) {
- config.params = params
- }
- if (query) {
- config.query = query
- }
- if (method === HTTP_METHOD.POST || method === HTTP_METHOD.PUT) {
- config.body = body
- }
- return this.fetch(url, config)
- }
- }
- export default ApiRequestService
|