reducer.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { SchemaSubject } from 'generated-sources';
  2. import { Action, SchemasState } from 'redux/interfaces';
  3. import * as actions from 'redux/actions';
  4. import { getType } from 'typesafe-actions';
  5. export const initialState: SchemasState = {
  6. byName: {},
  7. allNames: [],
  8. currentSchemaVersions: [],
  9. };
  10. const updateSchemaList = (
  11. state: SchemasState,
  12. payload: SchemaSubject[]
  13. ): SchemasState => {
  14. const initialMemo: SchemasState = {
  15. ...state,
  16. allNames: [],
  17. };
  18. return payload.reduce((memo: SchemasState, schema) => {
  19. if (!schema.subject) return memo;
  20. return {
  21. ...memo,
  22. byName: {
  23. ...memo.byName,
  24. [schema.subject]: {
  25. ...memo.byName[schema.subject],
  26. ...schema,
  27. },
  28. },
  29. allNames: [...memo.allNames, schema.subject],
  30. };
  31. }, initialMemo);
  32. };
  33. const addToSchemaList = (
  34. state: SchemasState,
  35. payload: SchemaSubject
  36. ): SchemasState => {
  37. const newState: SchemasState = {
  38. ...state,
  39. };
  40. newState.allNames.push(payload.subject);
  41. newState.byName[payload.subject] = { ...payload };
  42. return newState;
  43. };
  44. const deleteFromSchemaList = (
  45. state: SchemasState,
  46. payload: string
  47. ): SchemasState => {
  48. const newState: SchemasState = {
  49. ...state,
  50. };
  51. delete newState.byName[payload];
  52. newState.allNames = newState.allNames.filter((name) => name !== payload);
  53. return newState;
  54. };
  55. const reducer = (state = initialState, action: Action): SchemasState => {
  56. switch (action.type) {
  57. case 'GET_CLUSTER_SCHEMAS__SUCCESS':
  58. return updateSchemaList(state, action.payload);
  59. case 'GET_SCHEMA_VERSIONS__SUCCESS':
  60. return { ...state, currentSchemaVersions: action.payload };
  61. case 'POST_SCHEMA__SUCCESS':
  62. return addToSchemaList(state, action.payload);
  63. case getType(actions.deleteSchemaAction.success):
  64. return deleteFromSchemaList(state, action.payload);
  65. default:
  66. return state;
  67. }
  68. };
  69. export default reducer;