Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

353 Zeilen
12KB

  1. <%
  2. ' Api{{TABLE}}Controller: JSON API for the {{TABLE}} table. No layout, no cookies/CSRF (stateless).
  3. ' Generated {{DATE}} by scripts\GenerateApi.vbs (scripts\gen.cmd api). Spec: public/api/{{ROUTE}}.openapi.json
  4. '
  5. ' Routes (public/Default.asp):
  6. ' GET /api/{{ROUTE}} Index ?q= ?page= ?per_page= -> {"data":[...],"meta":{...}}
  7. ' GET /api/{{ROUTE}}/:id Show -> {"data":{...}}
  8. ' POST /api/{{ROUTE}} Create JSON body -> 201 + Location
  9. ' PUT /api/{{ROUTE}}/:id Update JSON body (full) -> 200
  10. ' PATCH /api/{{ROUTE}}/:id Update JSON body (only the fields sent change)
  11. ' DELETE /api/{{ROUTE}}/:id Delete -> 200 {"deleted":true}
  12. '
  13. ' Errors: {"error":{"message":"...","details":["..."]}} with 400, 404, 405 or 422.
  14. ' Body fields:
  15. {{DOC_FIELDS}}
  16. Const {{CONST}}_PER_PAGE = 10
  17. Const {{CONST}}_MAX_PER_PAGE = 100
  18. Class Api{{TABLE}}Controller_Class
  19. {{MEMBERS}}
  20. ' Dispatcher reads this to decide whether to wrap the output in the HTML layout
  21. Public Property Get useLayout()
  22. useLayout = False
  23. End Property
  24. Public Property Let useLayout(v)
  25. End Property
  26. '---------------------------------------------------------------
  27. Public Sub Index()
  28. Dim q, page, per_page, page_count, record_count, items, i, rowsJson
  29. q = Trim("" & Request.QueryString("q"))
  30. page = ToInt(Request.QueryString("page"), 1, 1, 1000000)
  31. per_page = ToInt(Request.QueryString("per_page"), {{CONST}}_PER_PAGE, 1, {{CONST}}_MAX_PER_PAGE)
  32. page_count = 1
  33. record_count = 0
  34. items = {{TABLE}}Repository().SearchTablePaged({{SEARCH_COLS}}, q, "{{ORDER_COL}}", per_page, page, page_count, record_count)
  35. rowsJson = ""
  36. For i = 0 To UBound(items)
  37. If i > 0 Then
  38. rowsJson = rowsJson & ","
  39. End If
  40. rowsJson = rowsJson & RowJson(items(i))
  41. Next
  42. SendRaw 200, "{""data"":[" & rowsJson & "],""meta"":{""page"":" & page & ",""per_page"":" & per_page & _
  43. ",""page_count"":" & page_count & ",""record_count"":" & record_count & "}}"
  44. End Sub
  45. Public Sub Show(id)
  46. Dim rec
  47. Set rec = LoadRecord(id)
  48. If rec Is Nothing Then Exit Sub
  49. SendRaw 200, "{""data"":" & RowJson(rec) & "}"
  50. End Sub
  51. Public Sub Create()
  52. Dim text, rec, errs
  53. If Not RequireMethod("POST") Then Exit Sub
  54. text = ReadBodyText()
  55. If IsEmpty(text) Then Exit Sub
  56. errs = ParseFields(text, False)
  57. If UBound(errs) >= 0 Then
  58. SendErrors 422, "Validation failed.", errs
  59. Exit Sub
  60. End If
  61. Set rec = New POBO_{{TABLE}}
  62. {{NEW_DEFAULTS}}
  63. ApplyFields rec
  64. On Error Resume Next
  65. {{TABLE}}Repository().AddNew rec
  66. If Err.Number <> 0 Then
  67. DbFailed Err.Number
  68. Exit Sub
  69. End If
  70. On Error GoTo 0
  71. Response.AddHeader "Location", "/api/{{ROUTE}}/" & rec.{{PK}}
  72. SendRaw 201, "{""data"":" & RowJson(rec) & "}"
  73. End Sub
  74. Public Sub Update(id)
  75. Dim text, rec, errs, partial, verb
  76. verb = UCase(Request.ServerVariables("REQUEST_METHOD"))
  77. If verb <> "PUT" And verb <> "PATCH" Then
  78. SendError 405, "Method not allowed. Use PUT or PATCH."
  79. Exit Sub
  80. End If
  81. text = ReadBodyText()
  82. If IsEmpty(text) Then Exit Sub
  83. partial = (verb = "PATCH")
  84. errs = ParseFields(text, partial)
  85. If UBound(errs) >= 0 Then
  86. SendErrors 422, "Validation failed.", errs
  87. Exit Sub
  88. End If
  89. Set rec = LoadRecord(id)
  90. If rec Is Nothing Then Exit Sub
  91. ApplyFields rec
  92. {{UPDATE_STAMPS}}
  93. On Error Resume Next
  94. {{TABLE}}Repository().Update rec
  95. If Err.Number <> 0 Then
  96. DbFailed Err.Number
  97. Exit Sub
  98. End If
  99. On Error GoTo 0
  100. SendRaw 200, "{""data"":" & RowJson(rec) & "}"
  101. End Sub
  102. Public Sub Delete(id)
  103. Dim rec
  104. If Not RequireMethod("DELETE") Then Exit Sub
  105. Set rec = LoadRecord(id)
  106. If rec Is Nothing Then Exit Sub
  107. On Error Resume Next
  108. {{TABLE}}Repository().Delete rec.{{PK}}
  109. If Err.Number <> 0 Then
  110. DbFailed Err.Number
  111. Exit Sub
  112. End If
  113. On Error GoTo 0
  114. SendRaw 200, "{""deleted"":true,""id"":" & CLng(rec.{{PK}}) & "}"
  115. End Sub
  116. '===============================================================
  117. ' Helpers
  118. '===============================================================
  119. ' JSON in/out uses core/lib.JsonLite.asp (pure VBScript). G3JSON dictionaries and G3DB interfered with each other
  120. ' under the AxonASP HTTP server, so no native JSON objects are used here (see AGENTS.md).
  121. Private Sub SendRaw(status, jsonText)
  122. Response.Clear
  123. Response.Status = StatusLine(status)
  124. Response.ContentType = "application/json"
  125. Response.Charset = "utf-8"
  126. Response.Write jsonText
  127. End Sub
  128. Private Sub SendError(status, message)
  129. SendErrors status, message, Array()
  130. End Sub
  131. Private Sub SendErrors(status, message, details)
  132. Dim i, list
  133. list = ""
  134. For i = 0 To UBound(details)
  135. If i > 0 Then
  136. list = list & ","
  137. End If
  138. list = list & JsonLite_Quote(details(i))
  139. Next
  140. SendRaw status, "{""error"":{""message"":" & JsonLite_Quote(message) & ",""details"":[" & list & "]}}"
  141. End Sub
  142. ' A failed write becomes a JSON 500 (the dispatcher would otherwise swallow the error and return an empty 200).
  143. ' The detail is not sent to the client; log it if you need it.
  144. Private Sub DbFailed(errNumber)
  145. Err.Clear
  146. On Error GoTo 0
  147. SendError 500, "Database error (" & errNumber & "). The change was not saved."
  148. End Sub
  149. Private Function StatusLine(status)
  150. Select Case status
  151. Case 200: StatusLine = "200 OK"
  152. Case 201: StatusLine = "201 Created"
  153. Case 400: StatusLine = "400 Bad Request"
  154. Case 404: StatusLine = "404 Not Found"
  155. Case 405: StatusLine = "405 Method Not Allowed"
  156. Case 422: StatusLine = "422 Unprocessable Entity"
  157. Case 500: StatusLine = "500 Internal Server Error"
  158. Case Else: StatusLine = status & " Error"
  159. End Select
  160. End Function
  161. Private Function RequireMethod(verb)
  162. RequireMethod = (UCase(Request.ServerVariables("REQUEST_METHOD")) = verb)
  163. If Not RequireMethod Then
  164. SendError 405, "Method not allowed. Use " & verb & "."
  165. End If
  166. End Function
  167. Private Function ToInt(v, dflt, lo, hi)
  168. Dim s
  169. s = Trim("" & v)
  170. ToInt = dflt
  171. If Len(s) > 0 Then
  172. If IsNumeric(s) Then
  173. ToInt = CLng(s)
  174. End If
  175. End If
  176. If ToInt < lo Then
  177. ToInt = lo
  178. End If
  179. If ToInt > hi Then
  180. ToInt = hi
  181. End If
  182. End Function
  183. ' Returns the record, or Nothing after sending a 404
  184. Private Function LoadRecord(id)
  185. Dim s
  186. Set LoadRecord = Nothing
  187. s = Trim("" & id)
  188. If Len(s) = 0 Or Not IsNumeric(s) Then
  189. SendError 404, "{{TABLE}} record not found."
  190. Exit Function
  191. End If
  192. On Error Resume Next
  193. Set LoadRecord = {{TABLE}}Repository().FindByID(CLng(s))
  194. If Err.Number <> 0 Then
  195. Err.Clear
  196. Set LoadRecord = Nothing
  197. On Error GoTo 0
  198. SendError 404, "{{TABLE}} record not found."
  199. Exit Function
  200. End If
  201. On Error GoTo 0
  202. End Function
  203. Private Function RowJson(rec)
  204. RowJson = {{ROW_JSON}}
  205. End Function
  206. ' Reads the raw request body as UTF-8 text and checks it is a JSON object. Sends 400 and returns False on failure.
  207. ' Only text crosses procedure boundaries: dictionaries passed between Subs/Functions were unreliable under the
  208. ' HTTP server (see AGENTS.md), so Apply parses the text itself.
  209. Private Function ReadBodyText()
  210. Dim n, text
  211. ReadBodyText = Empty
  212. n = Request.TotalBytes
  213. If n = 0 Then
  214. SendError 400, "Request body is empty. Send a JSON object."
  215. Exit Function
  216. End If
  217. ' AxonASP: BinaryRead returns one character per byte, so decode the UTF-8 by hand.
  218. text = Utf8Decode(CStr(Request.BinaryRead(n)))
  219. If JsonLite_Parse(text) Is Nothing Then
  220. SendError 400, "Body must be a valid JSON object."
  221. Exit Function
  222. End If
  223. ReadBodyText = text
  224. End Function
  225. ' Decodes a string holding raw UTF-8 bytes (one byte per character) into real Unicode text.
  226. Private Function Utf8Decode(ByVal s)
  227. Dim i, n, c, cp, extra, out, k, ok, b
  228. n = Len(s)
  229. out = ""
  230. i = 1
  231. Do While i <= n
  232. c = AscW(Mid(s, i, 1)) And 255
  233. If c < 128 Then
  234. out = out & Chr(c)
  235. i = i + 1
  236. Else
  237. extra = -1
  238. cp = 0
  239. If c >= 240 And c <= 247 Then
  240. extra = 3
  241. cp = c And 7
  242. ElseIf c >= 224 And c <= 239 Then
  243. extra = 2
  244. cp = c And 15
  245. ElseIf c >= 194 And c <= 223 Then
  246. extra = 1
  247. cp = c And 31
  248. End If
  249. ok = (extra > 0 And i + extra <= n)
  250. If ok Then
  251. For k = 1 To extra
  252. b = AscW(Mid(s, i + k, 1)) And 255
  253. If b < 128 Or b > 191 Then
  254. ok = False
  255. Else
  256. cp = cp * 64 + (b And 63)
  257. End If
  258. Next
  259. End If
  260. If ok And cp <= 1114111 Then
  261. If cp >= 65536 Then
  262. cp = cp - 65536
  263. out = out & ChrW(55296 + Int(cp / 1024)) & ChrW(56320 + (cp Mod 1024))
  264. Else
  265. out = out & ChrW(cp)
  266. End If
  267. i = i + extra + 1
  268. Else
  269. out = out & ChrW(65533) ' invalid byte sequence -> replacement character
  270. i = i + 1
  271. End If
  272. End If
  273. Loop
  274. Utf8Decode = out
  275. End Function
  276. ' Parses and validates the JSON body into the f_* members. Returns an array of error messages.
  277. ' partial=True (PATCH): only fields present are validated/applied; required fields are enforced when partial=False.
  278. ' Each field is read from its column name ("Name") or its camelCase form ("name").
  279. Private Function ParseFields(ByVal text, partial)
  280. Dim input, errs, n, v, k
  281. {{CLEAR_FIELDS}}
  282. Set input = JsonLite_Parse(text)
  283. ReDim errs(-1)
  284. n = -1
  285. {{PARSE_BODY}}
  286. ParseFields = errs
  287. End Function
  288. ' Copies the fields parsed by ParseFields onto the record (only the ones that were sent)
  289. Private Sub ApplyFields(rec)
  290. {{APPLY_BODY}}
  291. End Sub
  292. ' Server-side timestamp for CreatedAt / UpdatedAt columns
  293. Private Function NowStamp()
  294. Dim d
  295. d = Now()
  296. NowStamp = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _
  297. Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2)
  298. End Function
  299. ' Date column -> JSON string or null
  300. Private Function JsonDate(v)
  301. If IsNull(v) Then
  302. JsonDate = "null"
  303. Else
  304. If IsDate(v) Then
  305. v = CDate(v)
  306. JsonDate = JsonLite_Quote(Year(v) & "-" & Right("0" & Month(v), 2) & "-" & Right("0" & Day(v), 2) & " " & _
  307. Right("0" & Hour(v), 2) & ":" & Right("0" & Minute(v), 2) & ":" & Right("0" & Second(v), 2))
  308. Else
  309. JsonDate = JsonLite_Quote(CStr(v))
  310. End If
  311. End If
  312. End Function
  313. End Class
  314. Dim Api{{TABLE}}Controller_Class__Singleton
  315. Function Api{{TABLE}}Controller()
  316. If IsEmpty(Api{{TABLE}}Controller_Class__Singleton) Then
  317. Set Api{{TABLE}}Controller_Class__Singleton = New Api{{TABLE}}Controller_Class
  318. End If
  319. Set Api{{TABLE}}Controller = Api{{TABLE}}Controller_Class__Singleton
  320. End Function
  321. %>

Powered by TurnKey Linux.