Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

379 строки
14KB

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

Powered by TurnKey Linux.