11package controllers
22
33import (
4+ "bytes"
5+ "encoding/json"
46 "fmt"
57
68 "github.com/VersusControl/versus-incident/pkg/config"
@@ -11,23 +13,64 @@ import (
1113
1214func CreateIncident (c * fiber.Ctx ) error {
1315 cfg := config .GetConfig ()
16+ raw := c .Body ()
1417
1518 if cfg .Alert .DebugBody {
16- rawBody := c .Body ()
17-
1819 // Log the raw request body for debugging purposes
19- fmt .Println ("Raw Request Body:" , string (rawBody ))
20+ fmt .Println ("Raw Request Body:" , string (raw ))
2021 }
2122
22- body := & map [string ]interface {}{}
23+ // Detect if payload is an array; otherwise treat as single JSON object
24+ trimmed := bytes .TrimSpace (raw )
25+ if len (trimmed ) == 0 {
26+ return c .Status (fiber .StatusBadRequest ).JSON (fiber.Map {"error" : "Empty body" })
27+ }
28+
29+ // Handle JSON array
30+ if trimmed [0 ] == '[' {
31+ var records []map [string ]interface {}
32+ if err := json .Unmarshal (raw , & records ); err != nil {
33+ return c .Status (fiber .StatusBadRequest ).JSON (fiber.Map {"error" : "Invalid JSON array input" })
34+ }
35+ if len (records ) == 0 {
36+ return c .Status (fiber .StatusBadRequest ).JSON (fiber.Map {"error" : "No incidents found in array" })
37+ }
38+
39+ var err error
40+ if len (c .Queries ()) > 0 {
41+ overwriteVaule := c .Queries ()
42+ for _ , record := range records {
43+ // capture pointer per iteration
44+ rec := record
45+ if err = services .CreateIncident ("" , & rec , & overwriteVaule ); err != nil {
46+ break
47+ }
48+ }
49+ } else {
50+ for _ , record := range records {
51+ rec := record
52+ if err = services .CreateIncident ("" , & rec ); err != nil {
53+ break
54+ }
55+ }
56+ }
2357
58+ if err != nil {
59+ return c .Status (fiber .StatusInternalServerError ).JSON (fiber.Map {"error" : err .Error ()})
60+ }
61+
62+ return c .Status (fiber .StatusCreated ).JSON (fiber.Map {
63+ "status" : "Incidents created" ,
64+ "count" : len (records ),
65+ })
66+ }
67+
68+ body := & map [string ]interface {}{}
2469 if err := c .BodyParser (body ); err != nil {
2570 return c .Status (fiber .StatusBadRequest ).JSON (fiber.Map {"error" : "Invalid input" })
2671 }
2772
2873 var err error
29-
30- // If query parameters exist, get the value to overwrite the default configuration
3174 if len (c .Queries ()) > 0 {
3275 overwriteVaule := c .Queries ()
3376 err = services .CreateIncident ("" , body , & overwriteVaule )
0 commit comments