|
- <%
- ' Api{{TABLE}}Controller: JSON API for the {{TABLE}} table. No layout, no cookies/CSRF (stateless).
- ' Generated {{DATE}} by scripts\GenerateApi.vbs (scripts\gen.cmd api). Spec: public/api/{{ROUTE}}.openapi.json
- '
- ' Routes (public/Default.asp):
- ' GET /api/{{ROUTE}} Index ?q= ?page= ?per_page= -> {"data":[...],"meta":{...}}
- ' GET /api/{{ROUTE}}/:id Show -> {"data":{...}}
- ' POST /api/{{ROUTE}} Create JSON body -> 201 + Location
- ' PUT /api/{{ROUTE}}/:id Update JSON body (full) -> 200
- ' PATCH /api/{{ROUTE}}/:id Update JSON body (only the fields sent change)
- ' DELETE /api/{{ROUTE}}/:id Delete -> 200 {"deleted":true}
- '
- ' Errors: {"error":{"message":"...","details":["..."]}} with 400, 404, 405 or 422.
- ' Body fields:
- {{DOC_FIELDS}}
- Const {{CONST}}_PER_PAGE = 10
- Const {{CONST}}_MAX_PER_PAGE = 100
-
- Class Api{{TABLE}}Controller_Class
- {{MEMBERS}}
-
- ' Dispatcher reads this to decide whether to wrap the output in the HTML layout
- Public Property Get useLayout()
- useLayout = False
- End Property
-
- Public Property Let useLayout(v)
- End Property
-
- '---------------------------------------------------------------
- Public Sub Index()
- Dim q, page, per_page, page_count, record_count, items, i, rowsJson
- q = Trim("" & Request.QueryString("q"))
- page = ToInt(Request.QueryString("page"), 1, 1, 1000000)
- per_page = ToInt(Request.QueryString("per_page"), {{CONST}}_PER_PAGE, 1, {{CONST}}_MAX_PER_PAGE)
- page_count = 1
- record_count = 0
- items = {{TABLE}}Repository().SearchTablePaged({{SEARCH_COLS}}, q, "{{ORDER_COL}}", per_page, page, page_count, record_count)
-
- rowsJson = ""
- For i = 0 To UBound(items)
- If i > 0 Then
- rowsJson = rowsJson & ","
- End If
- rowsJson = rowsJson & RowJson(items(i))
- Next
-
- SendRaw 200, "{""data"":[" & rowsJson & "],""meta"":{""page"":" & page & ",""per_page"":" & per_page & _
- ",""page_count"":" & page_count & ",""record_count"":" & record_count & "}}"
- End Sub
-
- Public Sub Show(id)
- Dim rec
- Set rec = LoadRecord(id)
- If rec Is Nothing Then Exit Sub
- SendRaw 200, "{""data"":" & RowJson(rec) & "}"
- End Sub
-
- Public Sub Create()
- Dim text, rec, errs
- If Not RequireMethod("POST") Then Exit Sub
- text = ReadBodyText()
- If IsEmpty(text) Then Exit Sub
-
- errs = ParseFields(text, False)
- If UBound(errs) >= 0 Then
- SendErrors 422, "Validation failed.", errs
- Exit Sub
- End If
- Set rec = New POBO_{{TABLE}}
- {{NEW_DEFAULTS}}
- ApplyFields rec
-
- On Error Resume Next
- {{TABLE}}Repository().AddNew rec
- If Err.Number <> 0 Then
- DbFailed Err.Number
- Exit Sub
- End If
- On Error GoTo 0
- Response.AddHeader "Location", "/api/{{ROUTE}}/" & rec.{{PK}}
- SendRaw 201, "{""data"":" & RowJson(rec) & "}"
- End Sub
-
- Public Sub Update(id)
- Dim text, rec, errs, partial, verb
- verb = UCase(Request.ServerVariables("REQUEST_METHOD"))
- If verb <> "PUT" And verb <> "PATCH" Then
- SendError 405, "Method not allowed. Use PUT or PATCH."
- Exit Sub
- End If
- text = ReadBodyText()
- If IsEmpty(text) Then Exit Sub
- partial = (verb = "PATCH")
- errs = ParseFields(text, partial)
- If UBound(errs) >= 0 Then
- SendErrors 422, "Validation failed.", errs
- Exit Sub
- End If
- Set rec = LoadRecord(id)
- If rec Is Nothing Then Exit Sub
- ApplyFields rec
-
- {{UPDATE_STAMPS}}
- On Error Resume Next
- {{TABLE}}Repository().Update rec
- If Err.Number <> 0 Then
- DbFailed Err.Number
- Exit Sub
- End If
- On Error GoTo 0
- SendRaw 200, "{""data"":" & RowJson(rec) & "}"
- End Sub
-
- Public Sub Delete(id)
- Dim rec
- If Not RequireMethod("DELETE") Then Exit Sub
- Set rec = LoadRecord(id)
- If rec Is Nothing Then Exit Sub
- On Error Resume Next
- {{TABLE}}Repository().Delete rec.{{PK}}
- If Err.Number <> 0 Then
- DbFailed Err.Number
- Exit Sub
- End If
- On Error GoTo 0
- SendRaw 200, "{""deleted"":true,""id"":" & CLng(rec.{{PK}}) & "}"
- End Sub
-
- '===============================================================
- ' Helpers
- '===============================================================
- ' JSON in/out uses core/lib.JsonLite.asp (pure VBScript). G3JSON dictionaries and G3DB interfered with each other
- ' under the AxonASP HTTP server, so no native JSON objects are used here (see AGENTS.md).
- Private Sub SendRaw(status, jsonText)
- Response.Clear
- Response.Status = StatusLine(status)
- Response.ContentType = "application/json"
- Response.Charset = "utf-8"
- Response.Write jsonText
- End Sub
-
- Private Sub SendError(status, message)
- SendErrors status, message, Array()
- End Sub
-
- Private Sub SendErrors(status, message, details)
- Dim i, list
- list = ""
- For i = 0 To UBound(details)
- If i > 0 Then
- list = list & ","
- End If
- list = list & JsonLite_Quote(details(i))
- Next
- SendRaw status, "{""error"":{""message"":" & JsonLite_Quote(message) & ",""details"":[" & list & "]}}"
- End Sub
-
- ' A failed write becomes a JSON 500 (the dispatcher would otherwise swallow the error and return an empty 200).
- ' The detail is not sent to the client; log it if you need it.
- Private Sub DbFailed(errNumber)
- Err.Clear
- On Error GoTo 0
- SendError 500, "Database error (" & errNumber & "). The change was not saved."
- End Sub
-
- Private Function StatusLine(status)
- Select Case status
- Case 200: StatusLine = "200 OK"
- Case 201: StatusLine = "201 Created"
- Case 400: StatusLine = "400 Bad Request"
- Case 404: StatusLine = "404 Not Found"
- Case 405: StatusLine = "405 Method Not Allowed"
- Case 422: StatusLine = "422 Unprocessable Entity"
- Case 500: StatusLine = "500 Internal Server Error"
- Case Else: StatusLine = status & " Error"
- End Select
- End Function
-
- Private Function RequireMethod(verb)
- RequireMethod = (UCase(Request.ServerVariables("REQUEST_METHOD")) = verb)
- If Not RequireMethod Then
- SendError 405, "Method not allowed. Use " & verb & "."
- End If
- End Function
-
- Private Function ToInt(v, dflt, lo, hi)
- Dim s
- s = Trim("" & v)
- ToInt = dflt
- If Len(s) > 0 Then
- If IsNumeric(s) Then
- ToInt = CLng(s)
- End If
- End If
- If ToInt < lo Then
- ToInt = lo
- End If
- If ToInt > hi Then
- ToInt = hi
- End If
- End Function
-
- ' Returns the record, or Nothing after sending a 404
- Private Function LoadRecord(id)
- Dim s
- Set LoadRecord = Nothing
- s = Trim("" & id)
- If Len(s) = 0 Or Not IsNumeric(s) Then
- SendError 404, "{{TABLE}} record not found."
- Exit Function
- End If
-
- On Error Resume Next
- Set LoadRecord = {{TABLE}}Repository().FindByID(CLng(s))
- If Err.Number <> 0 Then
- Err.Clear
- Set LoadRecord = Nothing
- On Error GoTo 0
- SendError 404, "{{TABLE}} record not found."
- Exit Function
- End If
- On Error GoTo 0
- End Function
-
- Private Function RowJson(rec)
- RowJson = {{ROW_JSON}}
- End Function
-
- ' Reads the raw request body as UTF-8 text and checks it is a JSON object. Sends 400 and returns False on failure.
- ' Only text crosses procedure boundaries: dictionaries passed between Subs/Functions were unreliable under the
- ' HTTP server (see AGENTS.md), so Apply parses the text itself.
- Private Function ReadBodyText()
- Dim n, text
- ReadBodyText = Empty
- n = Request.TotalBytes
- If n = 0 Then
- SendError 400, "Request body is empty. Send a JSON object."
- Exit Function
- End If
- ' AxonASP: BinaryRead returns one character per byte, so decode the UTF-8 by hand.
- text = Utf8Decode(CStr(Request.BinaryRead(n)))
-
- If JsonLite_Parse(text) Is Nothing Then
- SendError 400, "Body must be a valid JSON object."
- Exit Function
- End If
- ReadBodyText = text
- End Function
-
- ' Decodes a string holding raw UTF-8 bytes (one byte per character) into real Unicode text.
- Private Function Utf8Decode(ByVal s)
- Dim i, n, c, cp, extra, out, k, ok, b
- n = Len(s)
- out = ""
- i = 1
- Do While i <= n
- c = AscW(Mid(s, i, 1)) And 255
- If c < 128 Then
- out = out & Chr(c)
- i = i + 1
- Else
- extra = -1
- cp = 0
- If c >= 240 And c <= 247 Then
- extra = 3
- cp = c And 7
- ElseIf c >= 224 And c <= 239 Then
- extra = 2
- cp = c And 15
- ElseIf c >= 194 And c <= 223 Then
- extra = 1
- cp = c And 31
- End If
- ok = (extra > 0 And i + extra <= n)
- If ok Then
- For k = 1 To extra
- b = AscW(Mid(s, i + k, 1)) And 255
- If b < 128 Or b > 191 Then
- ok = False
- Else
- cp = cp * 64 + (b And 63)
- End If
- Next
- End If
- If ok And cp <= 1114111 Then
- If cp >= 65536 Then
- cp = cp - 65536
- out = out & ChrW(55296 + Int(cp / 1024)) & ChrW(56320 + (cp Mod 1024))
- Else
- out = out & ChrW(cp)
- End If
- i = i + extra + 1
- Else
- out = out & ChrW(65533) ' invalid byte sequence -> replacement character
- i = i + 1
- End If
- End If
- Loop
- Utf8Decode = out
- End Function
-
- ' Parses and validates the JSON body into the f_* members. Returns an array of error messages.
- ' partial=True (PATCH): only fields present are validated/applied; required fields are enforced when partial=False.
- ' Each field is read from its column name ("Name") or its camelCase form ("name").
- Private Function ParseFields(ByVal text, partial)
- Dim input, errs, n, v, k
- {{CLEAR_FIELDS}}
- Set input = JsonLite_Parse(text)
- ReDim errs(-1)
- n = -1
- {{PARSE_BODY}}
- ParseFields = errs
- End Function
-
- ' Copies the fields parsed by ParseFields onto the record (only the ones that were sent)
- Private Sub ApplyFields(rec)
- {{APPLY_BODY}}
- End Sub
-
- ' Server-side timestamp for CreatedAt / UpdatedAt columns
- Private Function NowStamp()
- Dim d
- d = Now()
- NowStamp = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _
- Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2)
- End Function
-
- ' Date column -> JSON string or null
- Private Function JsonDate(v)
- If IsNull(v) Then
- JsonDate = "null"
- Else
- If IsDate(v) Then
- v = CDate(v)
- JsonDate = JsonLite_Quote(Year(v) & "-" & Right("0" & Month(v), 2) & "-" & Right("0" & Day(v), 2) & " " & _
- Right("0" & Hour(v), 2) & ":" & Right("0" & Minute(v), 2) & ":" & Right("0" & Second(v), 2))
- Else
- JsonDate = JsonLite_Quote(CStr(v))
- End If
- End If
- End Function
- End Class
-
- Dim Api{{TABLE}}Controller_Class__Singleton
- Function Api{{TABLE}}Controller()
- If IsEmpty(Api{{TABLE}}Controller_Class__Singleton) Then
- Set Api{{TABLE}}Controller_Class__Singleton = New Api{{TABLE}}Controller_Class
- End If
- Set Api{{TABLE}}Controller = Api{{TABLE}}Controller_Class__Singleton
- End Function
- %>
|