UNPKG

@statezero/core

Version:

The type-safe frontend client for StateZero - connect directly to your backend models with zero boilerplate

79 lines (78 loc) 3.16 kB
/** * This file was auto-generated. Do not make direct changes to the file. * Action: Process Data * App: django_app */ import axios from 'axios'; import { z } from 'zod'; import { configInstance, parseStateZeroError, serializeActionPayload } from '../../../../src'; import actionSchema from './process-data.schema.json' assert { type: 'json' }; /** * Zod schema for the input of processData. * NOTE: This is an object schema for validating the data payload. */ export const processDataInputSchema = z.object({ data: z.array(z.any()), operation: z.enum(["sum", "avg", "max", "min"]) }); /** * Zod schema for the response of processData. */ export const processDataResponseSchema = z.object({ operation: z.string(), result: z.number(), processed_count: z.number().int(), execution_time_ms: z.number().int() }); /** * Process a list of numbers with various mathematical operations * * @param any[] data - List of numbers to process * @param 'sum' | 'avg' | 'max' | 'min' operation - Mathematical operation to perform * @param {Object} [axiosOverrides] - Allows overriding Axios request parameters. * @returns {Promise<Object>} A promise that resolves with the action's result. */ export async function processData(data, operation, axiosOverrides = {}) { // Construct the data payload from the function arguments const rawPayload = { data, operation }; // Serialize payload - handles model instances (extracts PK), files, dates, etc. const payload = serializeActionPayload(rawPayload, actionSchema.input_properties); const config = configInstance.getConfig(); const backend = config.backendConfigs['default']; if (!backend) { throw new Error(`No backend configuration found for key: default`); } const baseUrl = backend.API_URL.replace(/\/+$/, ''); const actionUrl = `${baseUrl}/actions/process_data/`; const headers = backend.getAuthHeaders ? backend.getAuthHeaders() : {}; try { const response = await axios.post(actionUrl, payload, { headers: { 'Content-Type': 'application/json', ...headers }, ...axiosOverrides, }); return processDataResponseSchema.parse(response.data); } catch (error) { if (error instanceof z.ZodError) { throw new Error(`Process Data failed: Invalid response from server. Details: ${error.message}`); } if (error.response && error.response.data) { const parsedError = parseStateZeroError(error.response.data); if (Error.captureStackTrace) { Error.captureStackTrace(parsedError, processData); } throw parsedError; } else if (error.request) { throw new Error(`Process Data failed: No response received from server.`); } else { throw new Error(`Process Data failed: ${error.message}`); } } } export default processData; processData.actionName = 'process_data'; processData.title = 'Process Data'; processData.app = 'django_app'; processData.permissions = ['HasValidApiKey']; processData.configKey = 'default';