Skip to content

Why actions and handlers defined separately? #30

@finom

Description

@finom

This is one of the most interesting projects I've seen! Just want to make sure if I understand the logic behind json-render library (would be great if this repository would have Github Discussions).

My question is, why actions and handlers need to be defined separately?

const catalog = createCatalog({
  components: { /* ... */ },
  actions: {
    submit_form: {
      params: z.object({
        formId: z.string(),
      }),
      description: 'Submit a form',
    },
    export_data: {
      params: z.object({
        format: z.enum(['csv', 'pdf', 'json']),
        filters: z.object({
          dateRange: z.string().optional(),
        }).optional(),
      }),
    },
    navigate: {
      params: z.object({
        url: z.string(),
      }),
    },
  },
});

// ...
  const handlers = {
    submit_form: async (params) => {
      const response = await fetch('/api/submit', {
        method: 'POST',
        body: JSON.stringify({ formId: params.formId }),
      });
      return response.json();
    },
    
    export_data: async (params) => {
      const blob = await generateExport(params.format, params.filters);
      downloadBlob(blob, `export.${params.format}`);
    },
    
    navigate: (params) => {
      window.location.href = params.url;
    },
  };
// ...

Why not to use execute instead within actions object?

const catalog = createCatalog({
  components: { /* ... */ },
  actions: {
    submit_form: {
      params: z.object({
        formId: z.string(),
      }),
      description: 'Submit a form',
      execute: async (params) => {
        const response = await fetch('/api/submit', {
          method: 'POST',
          body: JSON.stringify({ formId: params.formId }),
        });
        return response.json();
      },
    },

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions