| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- import { Context } from '@nuxt/types/app'
- import { AnyJson, DataProviderArgs } from '~/types/interfaces'
- import { DENORMALIZER_TYPE, HTTP_METHOD, QUERY_TYPE } from '~/types/enums'
- import { providers } from '~/services/dataProvider/provider/_import'
- import ConstructUrl from '~/services/connection/constructUrl'
- import Connection from '~/services/connection/connection'
- import Serializer from '~/services/serializer/serializer'
- import ApiError from '~/services/utils/apiError'
- /**
- * Le DataProvider a pour rôle de fournir des données issues de l'API Opentalent
- */
- class DataProvider {
- private ctx !: Context;
- private readonly defaultArguments!: DataProviderArgs;
- constructor () {
- this.defaultArguments = {
- type: QUERY_TYPE.MODEL,
- progress: false
- }
- }
- /**
- * Initialise le contexte (la connection en particulier)
- * @param ctx
- */
- public initCtx (ctx: Context) {
- Connection.initConnector(ctx.$axios)
- this.ctx = ctx
- }
- /**
- * Exécute la requête et retourne la réponse désérialisée
- * @param args
- */
- public async invoke (args: DataProviderArgs): Promise<any> {
- try {
- // complete args with defaults
- args = { ...this.defaultArguments, ...args }
- DataProvider.startLoading(args)
- const url = ConstructUrl.invoke(args)
- const response = await DataProvider.sendRequest(url, args)
- const deserializeResponse = await Serializer.denormalize(response, DENORMALIZER_TYPE.HYDRA)
- return await this.provide(deserializeResponse, args)
- } catch (error) {
- throw new ApiError(500, error)
- }
- }
- /**
- * Signale le début du chargement à nuxt (si progress est true)
- * @param args
- */
- private static startLoading (args: DataProviderArgs) {
- if (args.progress) {
- const $nuxt = window.$nuxt
- $nuxt.$loading.start()
- }
- }
- /**
- * Send the request trough the Connection
- * @param url
- * @param args
- */
- public static sendRequest (url: string, args: DataProviderArgs): Promise<any> {
- return Connection.invoke(HTTP_METHOD.GET, url, args)
- }
- /**
- * Iterate over the available providers and invoke
- * the first one that support the given args
- * @param data
- * @param args
- */
- public provide (data: AnyJson, args: DataProviderArgs): any {
- for (const Provider of providers) {
- if (Provider.support(args)) {
- return new Provider(this.ctx, args).invoke(data)
- }
- }
- }
- }
- export default DataProvider
|