reducer.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { SchemaSubject } from 'generated-sources';
  2. import { Action, SchemasState } from 'redux/interfaces';
  3. export const initialState: SchemasState = {
  4. byName: {},
  5. allNames: [],
  6. currentSchemaVersions: [],
  7. };
  8. const updateSchemaList = (
  9. state: SchemasState,
  10. payload: SchemaSubject[]
  11. ): SchemasState => {
  12. const initialMemo: SchemasState = {
  13. ...state,
  14. allNames: [],
  15. };
  16. return payload.reduce((memo: SchemasState, schema) => {
  17. if (!schema.subject) return memo;
  18. return {
  19. ...memo,
  20. byName: {
  21. ...memo.byName,
  22. [schema.subject]: {
  23. ...memo.byName[schema.subject],
  24. ...schema,
  25. },
  26. },
  27. allNames: [...memo.allNames, schema.subject],
  28. };
  29. }, initialMemo);
  30. };
  31. const addToSchemaList = (
  32. state: SchemasState,
  33. payload: SchemaSubject
  34. ): SchemasState => {
  35. const newState: SchemasState = {
  36. ...state,
  37. };
  38. newState.allNames.push(payload.subject);
  39. newState.byName[payload.subject] = { ...payload };
  40. return newState;
  41. };
  42. const reducer = (state = initialState, action: Action): SchemasState => {
  43. switch (action.type) {
  44. case 'GET_CLUSTER_SCHEMAS__SUCCESS':
  45. return updateSchemaList(state, action.payload);
  46. case 'GET_SCHEMA_VERSIONS__SUCCESS':
  47. return { ...state, currentSchemaVersions: action.payload };
  48. case 'POST_SCHEMA__SUCCESS':
  49. return addToSchemaList(state, action.payload);
  50. default:
  51. return state;
  52. }
  53. };
  54. export default reducer;