Openstatus www.openstatus.dev
at main 91 lines 2.8 kB view raw
1import { z } from "zod"; 2 3import { 4 incidentCreatedSchema, 5 incidentResolvedSchema, 6 monitorDegradedSchema, 7 monitorFailedSchema, 8 monitorRecoveredSchema, 9 notificationSentSchema, 10} from "./action-schema"; 11import { ingestBaseEventSchema, pipeBaseResponseData } from "./base-validation"; 12 13/** 14 * The schema for the event object. 15 * It extends the base schema. It uses the `discriminatedUnion` method for faster 16 * evaluation to determine which schema to be used to parse the input. 17 * It also transforms the metadata object into a string. 18 * 19 * @todo: whenever a new action is added, it should be included to the discriminatedUnion 20 */ 21export const ingestActionEventSchema = z 22 .intersection( 23 // Unfortunately, the array cannot be dynamic, otherwise could be added to the Client 24 // and made available to devs as library 25 z.discriminatedUnion("action", [ 26 monitorRecoveredSchema, 27 monitorDegradedSchema, 28 monitorFailedSchema, 29 notificationSentSchema, 30 incidentCreatedSchema, 31 incidentResolvedSchema, 32 ]), 33 ingestBaseEventSchema, 34 ) 35 .transform((val) => ({ 36 ...val, 37 metadata: JSON.stringify(val.metadata), 38 })); 39 40/** 41 * The schema for the response object. 42 * It extends the base schema. It uses the `discriminatedUnion` method for faster 43 * evaluation to determine which schema to be used to parse the input. 44 * It also preprocesses the metadata string into the correct schema object. 45 * 46 * @todo: whenever a new action is added, it should be included to the discriminatedUnion 47 */ 48export const pipeActionResponseData = z.intersection( 49 z.discriminatedUnion("action", [ 50 monitorRecoveredSchema.extend({ 51 metadata: z.preprocess( 52 (val) => JSON.parse(String(val)), 53 monitorRecoveredSchema.shape.metadata, 54 ), 55 }), 56 monitorDegradedSchema.extend({ 57 metadata: z.preprocess( 58 (val) => JSON.parse(String(val)), 59 monitorDegradedSchema.shape.metadata, 60 ), 61 }), 62 monitorFailedSchema.extend({ 63 metadata: z.preprocess( 64 (val) => JSON.parse(String(val)), 65 monitorFailedSchema.shape.metadata, 66 ), 67 }), 68 notificationSentSchema.extend({ 69 metadata: z.preprocess( 70 (val) => JSON.parse(String(val)), 71 notificationSentSchema.shape.metadata, 72 ), 73 }), 74 incidentCreatedSchema.extend({ 75 metadata: z.preprocess( 76 (val) => JSON.parse(String(val)), 77 incidentCreatedSchema.shape.metadata, 78 ), 79 }), 80 incidentResolvedSchema.extend({ 81 metadata: z.preprocess( 82 (val) => JSON.parse(String(val)), 83 incidentResolvedSchema.shape.metadata, 84 ), 85 }), 86 ]), 87 pipeBaseResponseData, 88); 89 90export type IngestActionEvent = z.infer<typeof ingestActionEventSchema>; 91export type PipeActionResponseData = z.infer<typeof pipeActionResponseData>;