dataProvider.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { Context } from '@nuxt/types/app'
  2. import { AnyJson, DataProviderArgs } from '~/types/interfaces'
  3. import { DENORMALIZER_TYPE, HTTP_METHOD, QUERY_TYPE } from '~/types/enums'
  4. import { providers } from '~/services/dataProvider/provider/_import'
  5. import ConstructUrl from '~/services/connection/constructUrl'
  6. import Connection from '~/services/connection/connection'
  7. import Serializer from '~/services/serializer/serializer'
  8. import ApiError from '~/services/utils/apiError'
  9. /**
  10. * Le DataProvider a pour rôle de fournir des données issues de l'API Opentalent
  11. */
  12. class DataProvider {
  13. private ctx !: Context;
  14. private readonly defaultArguments!: DataProviderArgs;
  15. constructor () {
  16. this.defaultArguments = {
  17. type: QUERY_TYPE.MODEL,
  18. progress: false
  19. }
  20. }
  21. /**
  22. * Initialise le contexte (la connection en particulier)
  23. * @param ctx
  24. */
  25. public initCtx (ctx: Context) {
  26. Connection.initConnector(ctx.$axios)
  27. this.ctx = ctx
  28. }
  29. /**
  30. * Exécute la requête et retourne la réponse désérialisée
  31. * @param args
  32. */
  33. public async invoke (args: DataProviderArgs): Promise<any> {
  34. try {
  35. // complete args with defaults
  36. args = { ...this.defaultArguments, ...args }
  37. DataProvider.startLoading(args)
  38. const url = ConstructUrl.invoke(args)
  39. const response = await DataProvider.sendRequest(url, args)
  40. const deserializeResponse = await Serializer.denormalize(response, DENORMALIZER_TYPE.HYDRA)
  41. return await this.provide(deserializeResponse, args)
  42. } catch (error) {
  43. throw new ApiError(500, error)
  44. }
  45. }
  46. /**
  47. * Signale le début du chargement à nuxt (si progress est true)
  48. * @param args
  49. */
  50. private static startLoading (args: DataProviderArgs) {
  51. if (args.progress) {
  52. const $nuxt = window.$nuxt
  53. $nuxt.$loading.start()
  54. }
  55. }
  56. /**
  57. * Send the request trough the Connection
  58. * @param url
  59. * @param args
  60. */
  61. public static sendRequest (url: string, args: DataProviderArgs): Promise<any> {
  62. return Connection.invoke(HTTP_METHOD.GET, url, args)
  63. }
  64. /**
  65. * Iterate over the available providers and invoke
  66. * the first one that support the given args
  67. * @param data
  68. * @param args
  69. */
  70. public provide (data: AnyJson, args: DataProviderArgs): any {
  71. for (const Provider of providers) {
  72. if (Provider.support(args)) {
  73. return new Provider(this.ctx, args).invoke(data)
  74. }
  75. }
  76. }
  77. }
  78. export default DataProvider