constructUrl.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import {UrlArgs} from "~/types/interfaces";
  2. import {QUERY_TYPE} from "~/types/enums";
  3. import {Context} from "@nuxt/types/app";
  4. import {Model} from "@vuex-orm/core";
  5. class ConstructUrl{
  6. static ROOT = '/api/'
  7. private ctx !: Context
  8. constructor(ctx: Context) {
  9. this.ctx = ctx
  10. }
  11. invoke(args:UrlArgs): string{
  12. switch (args.type) {
  13. case QUERY_TYPE.DEFAULT:
  14. return this.getDefaultUrl(args.url)
  15. case QUERY_TYPE.ENUM:
  16. return this.getEnumUrl(args.enumType)
  17. case QUERY_TYPE.MODEL:
  18. return this.getModelUrl(args.model, args.root_model, args.root_id)
  19. default:
  20. throw new Error('url, model or enum must be defined');
  21. }
  22. }
  23. private getDefaultUrl(url?: string){
  24. if(typeof url === 'undefined')
  25. throw new Error('url must be defined');
  26. return String(ConstructUrl.ROOT + url).toString()
  27. }
  28. private getEnumUrl(enumType?: string){
  29. if(typeof enumType === 'undefined')
  30. throw new Error('enumType must be defined');
  31. return String(ConstructUrl.ROOT + 'enum/' + enumType).toString()
  32. }
  33. private getModelUrl(model ?: typeof Model, rootModel ?: typeof Model, rootId ?: number){
  34. if(typeof model === 'undefined')
  35. throw new Error('model must be defined');
  36. const repository = this.ctx.store.$repo(model);
  37. const entity = repository.getModel().$entity();
  38. if(typeof rootModel !== 'undefined'){
  39. if(typeof rootId === 'undefined')
  40. throw new Error('Root ID must be defined');
  41. const rootUrl = this.getModelUrl(rootModel) as string
  42. return String(`${rootUrl}/${rootId}/${entity}`).toString()
  43. }
  44. return String(ConstructUrl.ROOT + entity).toString()
  45. }
  46. }
  47. export default ConstructUrl