dataPersister.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import {hooks} from "~/services/dataPersister/hook/_import";
  2. import {AnyJson, DataPersisterArgs} from "~/types/interfaces";
  3. import {Context} from "@nuxt/types/app";
  4. import Connection from "~/services/connection/connection";
  5. import ConstructUrl from "~/services/connection/constructUrl";
  6. import {HTTP_METHOD} from "~/types/enums";
  7. import Serializer from "~/services/serializer/serializer";
  8. import ApiError from "~/services/utils/apiError";
  9. import DataProvider from "~/services/dataProvider/dataProvider";
  10. class DataPersister{
  11. private ctx !: Context
  12. private arguments!: DataPersisterArgs
  13. constructor() {
  14. this.sort()
  15. }
  16. initCtx(ctx:Context){
  17. Connection.initConnector(ctx.$axios)
  18. this.ctx = ctx
  19. }
  20. async invoke(args:DataPersisterArgs): Promise<any>{
  21. this.arguments = args
  22. try{
  23. this.preHook()
  24. this.arguments.data = this.serialization()
  25. const url = this.constructUrl()
  26. const response = await this.connection(url)
  27. this.provideResponse(response)
  28. }catch(error){
  29. throw new ApiError(error.response.status, error.response.data.detail)
  30. }
  31. }
  32. async preHook(){
  33. for(const hook of hooks){
  34. if(hook.support(this.arguments)){
  35. await new hook().invoke(this.arguments)
  36. }
  37. }
  38. }
  39. serialization(){
  40. const serializer = new Serializer()
  41. return serializer.normalize(this.arguments)
  42. }
  43. constructUrl(): string{
  44. const constructUrl = new ConstructUrl()
  45. return constructUrl.invoke(this.arguments)
  46. }
  47. connection(url: string): Promise<any>{
  48. const connection = new Connection()
  49. return connection.invoke(this.arguments.id ? HTTP_METHOD.PUT : HTTP_METHOD.POST, url, this.arguments)
  50. }
  51. async provideResponse(response: AnyJson){
  52. const dataProvider = new DataProvider()
  53. dataProvider.setArguments({
  54. type: this.arguments.type,
  55. url: this.arguments.url,
  56. enumType: this.arguments.enumType,
  57. model: this.arguments.model,
  58. root_model: this.arguments.root_model,
  59. id: this.arguments.id,
  60. root_id: this.arguments.root_id
  61. })
  62. const deserializeResponse = dataProvider.deserialization(response)
  63. return await dataProvider.provide(deserializeResponse)
  64. }
  65. sort(){
  66. hooks.sort(function(a, b) {
  67. if (a.priority > b.priority) {
  68. return 1
  69. }
  70. if (a.priority < b.priority) {
  71. return -1
  72. }
  73. return 0
  74. });
  75. }
  76. }
  77. export default DataPersister