Consolidated ASP Classic MVC framework from best components
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

612 lines
29KB

  1. '==============================================================
  2. ' GenerateApi.vbs (AxonASP CLI + G3DB edition)
  3. '
  4. ' Usage (runs under the AxonASP CLI in the container; gen.cmd runs GenerateRepo.vbs first):
  5. ' scripts\gen.cmd api /table:Products /pk:Id
  6. '
  7. ' Sets up a JSON API for one table:
  8. ' app/controllers/Api<Table>Controller.asp controller (list/search/paging, show, create, PUT, PATCH, delete)
  9. ' app/controllers/autoload_controllers.asp include line added
  10. ' app/models/autoload_models.asp POBO + repository include lines added
  11. ' core/lib.ControllerRegistry.asp controller whitelisted
  12. ' public/Default.asp 6 routes under /api/<table> added
  13. ' public/api/<table>.openapi.json OpenAPI spec (shows up in the /api/docs Swagger UI)
  14. ' api-tests/<table>.http sample requests (VS Code REST Client)
  15. '
  16. ' Notes: a JSON null is not accepted for a field (omit it instead). Needs app/models/POBO_<Table>.asp and <Table>Repository.asp (GenerateRepo.vbs). Refuses to overwrite an
  17. ' existing controller. Validation is derived from the column types and NOT NULL / DEFAULT; add business rules
  18. ' (ranges, lengths) in the generated controller by hand.
  19. '==============================================================
  20. Option Explicit
  21. ' AxonASP CLI: provide the WScript object (see _cli.vbs)
  22. Dim shimFso
  23. Set shimFso = CreateObject("Scripting.FileSystemObject")
  24. ExecuteGlobal shimFso.OpenTextFile(Server.MapPath("/scripts/_cli.vbs"), 1).ReadAll
  25. Dim fso, args, i, arg, parts, tableName, primaryKey, csKey, configPath
  26. Set fso = CreateObject("Scripting.FileSystemObject")
  27. Set args = WScript.Arguments
  28. csKey = "ConnectionString"
  29. configPath = Server.MapPath("/public/web.config")
  30. For i = 0 To args.Count - 1
  31. arg = args(i)
  32. If InStr(arg, ":") > 0 Then
  33. parts = Split(arg, ":", 2)
  34. Select Case LCase(Replace(parts(0), "/", ""))
  35. Case "table": tableName = parts(1)
  36. Case "pk": primaryKey = parts(1)
  37. End Select
  38. End If
  39. Next
  40. If Len(tableName) = 0 Or Len(primaryKey) = 0 Then
  41. WScript.Echo "Usage: scripts\gen.cmd api /table:<TableName> /pk:<PrimaryKey>"
  42. WScript.Quit 1
  43. End If
  44. If Not IsValidIdentifier(tableName) Or Not IsValidIdentifier(primaryKey) Then
  45. WScript.Echo "Error: table and primary key may only contain letters, numbers and underscores."
  46. WScript.Quit 1
  47. End If
  48. Dim ctrlPath, routeName, constName
  49. routeName = LCase(tableName)
  50. constName = "API_" & UCase(tableName)
  51. ctrlPath = Server.MapPath("/app/controllers/Api" & tableName & "Controller.asp")
  52. If fso.FileExists(ctrlPath) Then
  53. WScript.Echo "Error: " & ctrlPath & " already exists. Delete it first if you want to regenerate."
  54. WScript.Quit 1
  55. End If
  56. If Not fso.FileExists(Server.MapPath("/app/models/" & tableName & "Repository.asp")) Then
  57. WScript.Echo "Error: app/models/" & tableName & "Repository.asp not found. Run: scripts\gen.cmd repo /table:" & tableName & " /pk:" & primaryKey
  58. WScript.Quit 1
  59. End If
  60. '---------------- Connection + schema ----------------
  61. Dim connStr, p, dsn, db
  62. connStr = GetAppSetting(csKey, configPath)
  63. p = InStr(connStr, ":")
  64. If connStr = "nothing" Or p < 2 Then
  65. WScript.Echo "Error: ConnectionString not found or malformed in " & configPath
  66. WScript.Quit 1
  67. End If
  68. If LCase(Left(connStr, p - 1)) <> "sqlite" Then
  69. WScript.Echo "Error: schema discovery is implemented for SQLite only."
  70. WScript.Quit 1
  71. End If
  72. dsn = Mid(connStr, p + 1)
  73. Set db = Server.CreateObject("G3DB")
  74. If Not db.Open("sqlite", dsn) Then
  75. WScript.Echo "DB connection failed: " & db.LastError
  76. WScript.Quit 1
  77. End If
  78. ' cols(i) name, kinds(i) string|int|real|bool|date, needs(i) True when NOT NULL without DEFAULT, isPk(i)
  79. Dim cols(), kinds(), needs(), isPk(), dflts(), idx, rs, declType, notNull, dflt, pkFlag
  80. idx = -1
  81. Set rs = db.Query("PRAGMA table_info(" & tableName & ")")
  82. If IsEmpty(rs) Then
  83. WScript.Echo "Error reading table [" & tableName & "]: " & db.LastError
  84. WScript.Quit 1
  85. End If
  86. Do Until rs.EOF
  87. idx = idx + 1
  88. ReDim Preserve cols(idx), kinds(idx), needs(idx), isPk(idx), dflts(idx)
  89. cols(idx) = CStr(rs(1))
  90. declType = "" & rs(2)
  91. notNull = rs(3)
  92. dflt = rs(4)
  93. dflts(idx) = dflt
  94. pkFlag = rs(5)
  95. kinds(idx) = ApiKind(declType)
  96. isPk(idx) = (StrEqualCI(cols(idx), primaryKey) Or CLng(pkFlag) > 0)
  97. needs(idx) = (CLng(notNull) = 1 And IsNull(dflt) And Not isPk(idx))
  98. rs.MoveNext
  99. Loop
  100. rs.Close
  101. db.Close
  102. If idx < 0 Then
  103. WScript.Echo "No columns found for table [" & tableName & "]. Run the migrations first."
  104. WScript.Quit 1
  105. End If
  106. '---------------- Build the pieces ----------------
  107. Dim newDefaults, updStamps, dv, members, clearFields, parseBody, applyBody, rowJson, docFields, searchCols, orderCol, writable
  108. newDefaults = "" : updStamps = "" : members = "" : clearFields = "" : parseBody = "" : applyBody = "" : rowJson = "" : docFields = "" : searchCols = "" : orderCol = primaryKey
  109. writable = 0
  110. Dim q
  111. q = Chr(34)
  112. For i = 0 To idx
  113. Dim c, camel, fv
  114. c = cols(i)
  115. camel = LCase(Left(c, 1)) & Mid(c, 2)
  116. fv = "f_" & c
  117. ' ---- output JSON (all columns)
  118. If Len(rowJson) = 0 Then
  119. rowJson = q & "{" & q & q & camel & q & q & ":" & q & " & " & JsonExpr(c, kinds(i), isPk(i))
  120. Else
  121. rowJson = rowJson & " & _" & vbCrLf & " " & q & "," & q & q & camel & q & q & ":" & q & " & " & JsonExpr(c, kinds(i), isPk(i))
  122. End If
  123. ' ---- first string column is the default sort, string columns are searchable
  124. If kinds(i) = "string" And Not isPk(i) Then
  125. If Len(searchCols) > 0 Then searchCols = searchCols & ", "
  126. searchCols = searchCols & """" & c & """"
  127. If orderCol = primaryKey Then orderCol = c
  128. End If
  129. If isPk(i) Then
  130. docFields = docFields & "' " & camel & " (read-only primary key)" & vbCrLf
  131. ElseIf IsStampCol(c, kinds(i)) Then
  132. ' CreatedAt / UpdatedAt are managed by the server
  133. If LCase(c) = "createdat" Then
  134. newDefaults = newDefaults & " rec." & c & " = NowStamp()" & vbCrLf
  135. Else
  136. newDefaults = newDefaults & " rec." & c & " = NowStamp()" & vbCrLf
  137. updStamps = updStamps & " rec." & c & " = NowStamp()" & vbCrLf
  138. End If
  139. docFields = docFields & "' " & camel & " (set by the server)" & vbCrLf
  140. Else
  141. writable = writable + 1
  142. dv = DefaultLiteral(dflts(i))
  143. If Len(dv) > 0 Then
  144. newDefaults = newDefaults & " rec." & c & " = " & dv & vbCrLf
  145. End If
  146. members = members & " Private " & fv & vbCrLf
  147. clearFields = clearFields & " " & fv & " = Empty" & vbCrLf
  148. parseBody = parseBody & BuildParse(c, camel, fv, kinds(i), needs(i))
  149. applyBody = applyBody & " If Not IsEmpty(" & fv & ") Then" & vbCrLf & _
  150. " rec." & c & " = " & fv & vbCrLf & _
  151. " End If" & vbCrLf
  152. docFields = docFields & "' " & c & " (" & kinds(i) & Pick(needs(i), ", required", "") & ")" & vbCrLf
  153. End If
  154. Next
  155. rowJson = rowJson & " & ""}"""
  156. If Len(searchCols) = 0 Then
  157. searchCols = "Empty"
  158. Else
  159. searchCols = "Array(" & searchCols & ")"
  160. End If
  161. docFields = Left(docFields, Len(docFields) - 2)
  162. '---------------- Write the controller ----------------
  163. Dim t
  164. t = ReadTemplate("Api.tpl.asp")
  165. t = Replace(t, "{{TABLE}}", tableName)
  166. t = Replace(t, "{{PK}}", primaryKey)
  167. t = Replace(t, "{{ROUTE}}", routeName)
  168. t = Replace(t, "{{CONST}}", constName)
  169. If Len(updStamps) = 0 Then
  170. t = Replace(t, "{{UPDATE_STAMPS}}" & vbLf, "")
  171. t = Replace(t, "{{UPDATE_STAMPS}}" & vbCrLf, "")
  172. Else
  173. t = Replace(t, "{{UPDATE_STAMPS}}", Left(updStamps, Len(updStamps) - 2))
  174. End If
  175. If Len(newDefaults) = 0 Then
  176. t = Replace(t, "{{NEW_DEFAULTS}}" & vbCrLf, "")
  177. Else
  178. t = Replace(t, "{{NEW_DEFAULTS}}", Left(newDefaults, Len(newDefaults) - 2))
  179. End If
  180. t = Replace(t, "{{DATE}}", CStr(Now()))
  181. t = Replace(t, "{{DOC_FIELDS}}", docFields)
  182. t = Replace(t, "{{MEMBERS}}", Left(members, Len(members) - 2))
  183. t = Replace(t, "{{CLEAR_FIELDS}}", Left(clearFields, Len(clearFields) - 2))
  184. t = Replace(t, "{{PARSE_BODY}}", parseBody)
  185. t = Replace(t, "{{APPLY_BODY}}", Left(applyBody, Len(applyBody) - 2))
  186. t = Replace(t, "{{SEARCH_COLS}}", searchCols)
  187. t = Replace(t, "{{ORDER_COL}}", orderCol)
  188. t = Replace(t, "{{ROW_JSON}}", rowJson)
  189. WriteFile ctrlPath, t
  190. WScript.Echo "Controller: " & ctrlPath
  191. '---------------- Wire it up ----------------
  192. AppendIfMissing "/app/models/autoload_models.asp", "POBO_" & tableName & ".asp", "<!--#include file=""POBO_" & tableName & ".asp"" -->"
  193. AppendIfMissing "/app/models/autoload_models.asp", tableName & "Repository.asp", "<!--#include file=""" & tableName & "Repository.asp"" -->"
  194. AppendIfMissing "/app/controllers/autoload_controllers.asp", "Api" & tableName & "Controller.asp", "<!--#include file=""Api" & tableName & "Controller.asp"" -->"
  195. WScript.Echo "Includes: autoload_models.asp, autoload_controllers.asp"
  196. InsertAfterLine "/core/lib.ControllerRegistry.asp", "RegisterController ""errorcontroller""", "api" & LCase(tableName) & "controller", _
  197. " RegisterController ""api" & LCase(tableName) & "controller"""
  198. WScript.Echo "Registry: api" & LCase(tableName) & "controller whitelisted"
  199. Dim r
  200. r = vbTab & "' " & tableName & " JSON API (generated by GenerateApi.vbs)" & vbCrLf & _
  201. vbTab & "router.AddRoute ""GET"", ""/api/" & routeName & """, ""Api" & tableName & "Controller"", ""Index""" & vbCrLf & _
  202. vbTab & "router.AddRoute ""POST"", ""/api/" & routeName & """, ""Api" & tableName & "Controller"", ""Create""" & vbCrLf & _
  203. vbTab & "router.AddRoute ""GET"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Show""" & vbCrLf & _
  204. vbTab & "router.AddRoute ""PUT"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Update""" & vbCrLf & _
  205. vbTab & "router.AddRoute ""PATCH"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Update""" & vbCrLf & _
  206. vbTab & "router.AddRoute ""DELETE"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Delete""" & vbCrLf & vbCrLf
  207. InsertBeforeLine "/public/Default.asp", "' Dispatch the request", "Api" & tableName & "Controller", r
  208. WScript.Echo "Routes: /api/" & routeName & " and /api/" & routeName & "/:id added to public/Default.asp"
  209. '---------------- Spec + sample requests ----------------
  210. Dim specDir, specPath
  211. specDir = Server.MapPath("/public/api")
  212. If Not fso.FolderExists(specDir) Then fso.CreateFolder specDir
  213. specPath = specDir & "/" & routeName & ".openapi.json"
  214. WriteFile specPath, BuildSpec()
  215. WScript.Echo "OpenAPI spec: " & specPath
  216. Dim httpDir, httpPath
  217. httpDir = Server.MapPath("/api-tests")
  218. If Not fso.FolderExists(httpDir) Then fso.CreateFolder httpDir
  219. httpPath = httpDir & "/" & routeName & ".http"
  220. WriteFile httpPath, BuildHttp()
  221. WScript.Echo "Sample calls: " & httpPath
  222. WScript.Echo ""
  223. WScript.Echo "Done. Restart the container (docker restart axonasp), then open /api/docs and pick '" & tableName & "' in the spec list."
  224. '==============================================================
  225. ' Code generation
  226. '==============================================================
  227. Function BuildParse(c, camel, fv, kind, required)
  228. Dim s, label
  229. label = c
  230. s = " k = """"" & vbCrLf
  231. s = s & " If input.Exists(""" & c & """) Then" & vbCrLf
  232. s = s & " k = """ & c & """" & vbCrLf
  233. If camel <> c Then
  234. s = s & " ElseIf input.Exists(""" & camel & """) Then" & vbCrLf
  235. s = s & " k = """ & camel & """" & vbCrLf
  236. End If
  237. s = s & " End If" & vbCrLf
  238. s = s & " If Len(k) > 0 Then" & vbCrLf
  239. s = s & " v = input.Item(k)" & vbCrLf
  240. Select Case kind
  241. Case "string"
  242. s = s & " v = Trim("""" & v)" & vbCrLf
  243. If required Then
  244. s = s & " If Len(v) = 0 Then" & vbCrLf
  245. s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " is required.""" & vbCrLf
  246. s = s & " End If" & vbCrLf
  247. End If
  248. s = s & " " & fv & " = v" & vbCrLf
  249. Case "int", "real"
  250. s = s & " If VarType(v) = 11 Then" & vbCrLf
  251. s = s & " v = CLng(v) * -1" & vbCrLf
  252. s = s & " End If" & vbCrLf
  253. s = s & " If IsNumeric(v) And Not IsNull(v) And VarType(v) <> 8 Then" & vbCrLf
  254. If kind = "int" Then
  255. s = s & " If CDbl(v) <> Int(CDbl(v)) Then" & vbCrLf
  256. s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a whole number.""" & vbCrLf
  257. s = s & " Else" & vbCrLf
  258. s = s & " " & fv & " = CLng(v)" & vbCrLf
  259. s = s & " End If" & vbCrLf
  260. Else
  261. s = s & " " & fv & " = CDbl(v)" & vbCrLf
  262. End If
  263. s = s & " Else" & vbCrLf
  264. s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a number.""" & vbCrLf
  265. s = s & " End If" & vbCrLf
  266. Case "bool"
  267. s = s & " If VarType(v) = 11 Then" & vbCrLf
  268. s = s & " " & fv & " = v" & vbCrLf
  269. s = s & " ElseIf IsNumeric(v) And Not IsNull(v) And VarType(v) <> 8 Then" & vbCrLf
  270. s = s & " " & fv & " = (CDbl(v) <> 0)" & vbCrLf
  271. s = s & " Else" & vbCrLf
  272. s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be true or false.""" & vbCrLf
  273. s = s & " End If" & vbCrLf
  274. Case "date"
  275. s = s & " If IsDate(v) Then" & vbCrLf
  276. s = s & " " & fv & " = CDate(v)" & vbCrLf
  277. s = s & " Else" & vbCrLf
  278. s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a date.""" & vbCrLf
  279. s = s & " End If" & vbCrLf
  280. End Select
  281. If required Then
  282. s = s & " ElseIf Not partial Then" & vbCrLf
  283. s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " is required.""" & vbCrLf
  284. End If
  285. s = s & " End If" & vbCrLf & vbCrLf
  286. BuildParse = s
  287. End Function
  288. ' VBScript expression (generator output) that renders column c of "rec" as a JSON value
  289. Function JsonExpr(c, kind, pk)
  290. If pk Or kind = "int" Then
  291. JsonExpr = "CLng(rec." & c & ")"
  292. ElseIf kind = "real" Then
  293. JsonExpr = "JsonLite_Num(rec." & c & ")"
  294. ElseIf kind = "bool" Then
  295. JsonExpr = "LCase(CStr(CBool(rec." & c & ")))"
  296. ElseIf kind = "date" Then
  297. JsonExpr = "JsonDate(rec." & c & ")"
  298. Else
  299. JsonExpr = "JsonLite_Quote(rec." & c & ")"
  300. End If
  301. End Function
  302. Function BuildSpec()
  303. Dim sch, inp, req, k, nm, ty, ex, exs, sep
  304. sch = "" : inp = "" : req = "" : exs = ""
  305. For k = 0 To idx
  306. nm = LCase(Left(cols(k), 1)) & Mid(cols(k), 2)
  307. ty = SpecType(kinds(k), isPk(k))
  308. If Len(sch) > 0 Then sch = sch & "," & vbCrLf
  309. sch = sch & " """ & nm & """: " & ty
  310. If Not isPk(k) And Not IsStampCol(cols(k), kinds(k)) Then
  311. If Len(inp) > 0 Then inp = inp & "," & vbCrLf
  312. inp = inp & " """ & cols(k) & """: " & ty
  313. If needs(k) Then
  314. If Len(req) > 0 Then req = req & ", "
  315. req = req & """" & cols(k) & """"
  316. End If
  317. If Len(exs) > 0 Then exs = exs & ", "
  318. exs = exs & """" & cols(k) & """: " & SampleValue(kinds(k))
  319. End If
  320. Next
  321. Dim reqLine
  322. reqLine = ""
  323. If Len(req) > 0 Then reqLine = " ""required"": [" & req & "]," & vbCrLf
  324. Dim T, R
  325. T = tableName : R = routeName
  326. Dim s
  327. s = "{" & vbCrLf
  328. s = s & " ""openapi"": ""3.0.3""," & vbCrLf
  329. s = s & " ""info"": { ""title"": """ & T & " API"", ""version"": ""1.0.0"", ""description"": ""Generated by GenerateApi.vbs from the " & T & " table. Stateless: no auth or CSRF. Request fields use the column names (camelCase also accepted); responses use camelCase."" }," & vbCrLf
  330. s = s & " ""servers"": [{ ""url"": ""/"" }]," & vbCrLf
  331. s = s & " ""tags"": [{ ""name"": """ & T & """ }]," & vbCrLf
  332. s = s & " ""paths"": {" & vbCrLf
  333. s = s & " ""/api/" & R & """: {" & vbCrLf
  334. s = s & " ""get"": { ""tags"": [""" & T & """], ""summary"": ""List (search + paging)""," & vbCrLf
  335. s = s & " ""parameters"": [" & vbCrLf
  336. s = s & " { ""name"": ""q"", ""in"": ""query"", ""schema"": { ""type"": ""string"" }, ""description"": ""Case-insensitive match on the text columns"" }," & vbCrLf
  337. s = s & " { ""name"": ""page"", ""in"": ""query"", ""schema"": { ""type"": ""integer"", ""minimum"": 1, ""default"": 1 } }," & vbCrLf
  338. s = s & " { ""name"": ""per_page"", ""in"": ""query"", ""schema"": { ""type"": ""integer"", ""minimum"": 1, ""maximum"": 100, ""default"": 10 } }" & vbCrLf
  339. s = s & " ]," & vbCrLf
  340. s = s & " ""responses"": { ""200"": { ""description"": ""A page of records"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/List"" } } } } } }," & vbCrLf
  341. s = s & " ""post"": { ""tags"": [""" & T & """], ""summary"": ""Create""," & vbCrLf
  342. s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {" & exs & "} } } }," & vbCrLf
  343. s = s & " ""responses"": { ""201"": { ""description"": ""Created (Location header has the new URL)"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }" & vbCrLf
  344. s = s & " }," & vbCrLf
  345. s = s & " ""/api/" & R & "/{id}"": {" & vbCrLf
  346. s = s & " ""parameters"": [{ ""name"": ""id"", ""in"": ""path"", ""required"": true, ""schema"": { ""type"": ""integer"" } }]," & vbCrLf
  347. s = s & " ""get"": { ""tags"": [""" & T & """], ""summary"": ""Get one""," & vbCrLf
  348. s = s & " ""responses"": { ""200"": { ""description"": ""The record"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""404"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf
  349. s = s & " ""put"": { ""tags"": [""" & T & """], ""summary"": ""Replace (required fields enforced)""," & vbCrLf
  350. s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {" & exs & "} } } }," & vbCrLf
  351. s = s & " ""responses"": { ""200"": { ""description"": ""Updated"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""404"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf
  352. s = s & " ""patch"": { ""tags"": [""" & T & """], ""summary"": ""Partial update (only fields sent change)""," & vbCrLf
  353. s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {} } } }," & vbCrLf
  354. s = s & " ""responses"": { ""200"": { ""description"": ""Updated"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""400"": { ""$ref"": ""#/components/responses/Error"" }, ""404"": { ""$ref"": ""#/components/responses/Error"" }, ""422"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf
  355. s = s & " ""delete"": { ""tags"": [""" & T & """], ""summary"": ""Delete""," & vbCrLf
  356. s = s & " ""responses"": { ""200"": { ""description"": ""Deleted"", ""content"": { ""application/json"": { ""schema"": { ""type"": ""object"", ""properties"": { ""deleted"": { ""type"": ""boolean"" }, ""id"": { ""type"": ""integer"" } } } } } }, ""404"": { ""$ref"": ""#/components/responses/Error"" } } }" & vbCrLf
  357. s = s & " }" & vbCrLf
  358. s = s & " }," & vbCrLf
  359. s = s & " ""components"": {" & vbCrLf
  360. s = s & " ""schemas"": {" & vbCrLf
  361. s = s & " ""Record"": { ""type"": ""object"", ""properties"": {" & vbCrLf & sch & vbCrLf & " } }," & vbCrLf
  362. s = s & " ""Input"": { ""type"": ""object""," & vbCrLf & reqLine & " ""properties"": {" & vbCrLf & inp & vbCrLf & " } }," & vbCrLf
  363. s = s & " ""Envelope"": { ""type"": ""object"", ""properties"": { ""data"": { ""$ref"": ""#/components/schemas/Record"" } } }," & vbCrLf
  364. s = s & " ""List"": { ""type"": ""object"", ""properties"": { ""data"": { ""type"": ""array"", ""items"": { ""$ref"": ""#/components/schemas/Record"" } }, ""meta"": { ""type"": ""object"", ""properties"": { ""page"": { ""type"": ""integer"" }, ""per_page"": { ""type"": ""integer"" }, ""page_count"": { ""type"": ""integer"" }, ""record_count"": { ""type"": ""integer"" } } } } }," & vbCrLf
  365. s = s & " ""Error"": { ""type"": ""object"", ""properties"": { ""error"": { ""type"": ""object"", ""properties"": { ""message"": { ""type"": ""string"" }, ""details"": { ""type"": ""array"", ""items"": { ""type"": ""string"" } } } } } }" & vbCrLf
  366. s = s & " }," & vbCrLf
  367. s = s & " ""responses"": { ""Error"": { ""description"": ""Error"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Error"" } } } } }" & vbCrLf
  368. s = s & " }" & vbCrLf
  369. s = s & "}" & vbCrLf
  370. BuildSpec = s
  371. End Function
  372. Function BuildHttp()
  373. Dim k, ex, h
  374. ex = ""
  375. For k = 0 To idx
  376. If Not isPk(k) And Not IsStampCol(cols(k), kinds(k)) Then
  377. If Len(ex) > 0 Then ex = ex & ", "
  378. ex = ex & """" & cols(k) & """: " & SampleValue(kinds(k))
  379. End If
  380. Next
  381. h = "### " & tableName & " JSON API. Use with the VS Code ""REST Client"" extension (or any .http runner)." & vbLf
  382. h = h & "@base = http://localhost:8801" & vbLf & vbLf
  383. h = h & "### List (q = text search, page, per_page max 100)" & vbLf & "GET {{base}}/api/" & routeName & "?page=1&per_page=5" & vbLf & vbLf
  384. h = h & "### Show" & vbLf & "GET {{base}}/api/" & routeName & "/1" & vbLf & vbLf
  385. h = h & "### Create -> 201 + Location header" & vbLf & "POST {{base}}/api/" & routeName & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ " & ex & " }" & vbLf & vbLf
  386. h = h & "### Replace (required fields enforced)" & vbLf & "PUT {{base}}/api/" & routeName & "/1" & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ " & ex & " }" & vbLf & vbLf
  387. h = h & "### Partial update (only the fields sent change)" & vbLf & "PATCH {{base}}/api/" & routeName & "/1" & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ }" & vbLf & vbLf
  388. h = h & "### Delete" & vbLf & "DELETE {{base}}/api/" & routeName & "/1" & vbLf
  389. BuildHttp = h
  390. End Function
  391. Function SpecType(kind, pk)
  392. If pk Or kind = "int" Then
  393. SpecType = "{ ""type"": ""integer"" }"
  394. ElseIf kind = "real" Then
  395. SpecType = "{ ""type"": ""number"" }"
  396. ElseIf kind = "bool" Then
  397. SpecType = "{ ""type"": ""boolean"" }"
  398. ElseIf kind = "date" Then
  399. SpecType = "{ ""type"": ""string"", ""format"": ""date-time"", ""nullable"": true }"
  400. Else
  401. SpecType = "{ ""type"": ""string"" }"
  402. End If
  403. End Function
  404. ' SQLite DEFAULT text -> VBScript literal ("" when it is not a plain number or quoted string)
  405. Function DefaultLiteral(d)
  406. Dim s
  407. DefaultLiteral = ""
  408. If IsNull(d) Then Exit Function
  409. s = Trim("" & d)
  410. If Len(s) = 0 Then Exit Function
  411. If IsNumeric(s) Then
  412. DefaultLiteral = s
  413. ElseIf Len(s) >= 2 And Left(s, 1) = "'" And Right(s, 1) = "'" Then
  414. s = Mid(s, 2, Len(s) - 2)
  415. DefaultLiteral = """" & Replace(Replace(s, "''", "'"), """", """""") & """"
  416. End If
  417. End Function
  418. Function SampleValue(kind)
  419. Select Case kind
  420. Case "int": SampleValue = "1"
  421. Case "real": SampleValue = "9.99"
  422. Case "bool": SampleValue = "true"
  423. Case "date": SampleValue = """2026-01-01 00:00:00"""
  424. Case Else: SampleValue = """text"""
  425. End Select
  426. End Function
  427. '==============================================================
  428. ' File helpers
  429. '==============================================================
  430. Function ReadTemplate(name)
  431. Dim ts
  432. Set ts = fso.OpenTextFile(Server.MapPath("/scripts/templates/" & name), 1)
  433. ReadTemplate = ts.ReadAll
  434. ts.Close
  435. End Function
  436. Function ReadFile(path)
  437. Dim ts
  438. Set ts = fso.OpenTextFile(Server.MapPath(path), 1)
  439. ReadFile = ts.ReadAll
  440. ts.Close
  441. End Function
  442. Sub WriteFile(path, text)
  443. Dim tf
  444. Set tf = fso.CreateTextFile(path, True)
  445. tf.Write text
  446. tf.Close
  447. End Sub
  448. Function EolOf(text)
  449. If InStr(text, vbCrLf) > 0 Then
  450. EolOf = vbCrLf
  451. Else
  452. EolOf = vbLf
  453. End If
  454. End Function
  455. Function WithEol(text, eol)
  456. WithEol = Replace(Replace(text, vbCrLf, vbLf), vbLf, eol)
  457. End Function
  458. ' Appends a line to the file unless "marker" is already in it
  459. Sub AppendIfMissing(path, marker, line)
  460. Dim s, eol
  461. s = ReadFile(path)
  462. If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub
  463. eol = EolOf(s)
  464. If Right(s, 1) <> vbLf Then s = s & eol
  465. WriteFile Server.MapPath(path), s & line & eol
  466. End Sub
  467. ' Inserts newText on a new line after the first line containing anchor (unless marker is already present)
  468. Sub InsertAfterLine(path, anchor, marker, newText)
  469. Dim s, eol, pos, eolPos
  470. s = ReadFile(path)
  471. If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub
  472. eol = EolOf(s)
  473. pos = InStr(1, s, anchor, vbTextCompare)
  474. If pos = 0 Then
  475. WScript.Echo "Warning: anchor '" & anchor & "' not found in " & path & "; add the line yourself: " & newText
  476. Exit Sub
  477. End If
  478. eolPos = InStr(pos, s, eol)
  479. s = Left(s, eolPos - 1) & eol & newText & Mid(s, eolPos)
  480. WriteFile Server.MapPath(path), s
  481. End Sub
  482. ' Inserts newText before the line containing anchor (unless marker is already present)
  483. Sub InsertBeforeLine(path, anchor, marker, newText)
  484. Dim s, eol, pos, lineStart
  485. s = ReadFile(path)
  486. If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub
  487. eol = EolOf(s)
  488. pos = InStr(1, s, anchor, vbTextCompare)
  489. If pos = 0 Then
  490. WScript.Echo "Warning: anchor '" & anchor & "' not found in " & path & "; add the routes yourself:" & vbCrLf & newText
  491. Exit Sub
  492. End If
  493. lineStart = InStrRev(s, eol, pos)
  494. If lineStart = 0 Then
  495. lineStart = 1
  496. Else
  497. lineStart = lineStart + Len(eol)
  498. End If
  499. s = Left(s, lineStart - 1) & WithEol(newText, eol) & Mid(s, lineStart)
  500. WriteFile Server.MapPath(path), s
  501. End Sub
  502. '==============================================================
  503. ' Misc helpers
  504. '==============================================================
  505. ' SQLite declared type -> string | int | real | bool | date
  506. Function ApiKind(declType)
  507. Dim t
  508. t = UCase("" & declType)
  509. If InStr(t, "BOOL") > 0 Then
  510. ApiKind = "bool"
  511. ElseIf InStr(t, "DATE") > 0 Or InStr(t, "TIME") > 0 Then
  512. ApiKind = "date"
  513. ElseIf InStr(t, "CHAR") > 0 Or InStr(t, "CLOB") > 0 Or InStr(t, "TEXT") > 0 Then
  514. ApiKind = "string"
  515. ElseIf InStr(t, "INT") > 0 Then
  516. ApiKind = "int"
  517. ElseIf InStr(t, "REAL") > 0 Or InStr(t, "FLOA") > 0 Or InStr(t, "DOUB") > 0 Or InStr(t, "NUM") > 0 Or InStr(t, "DEC") > 0 Then
  518. ApiKind = "real"
  519. Else
  520. ApiKind = "string"
  521. End If
  522. End Function
  523. ' CreatedAt / UpdatedAt text or date columns are filled in by the server, not accepted from clients
  524. Function IsStampCol(name, kind)
  525. IsStampCol = False
  526. If kind = "string" Or kind = "date" Then
  527. If LCase(name) = "createdat" Or LCase(name) = "updatedat" Then IsStampCol = True
  528. End If
  529. End Function
  530. Function Pick(cond, a, b)
  531. If cond Then
  532. Pick = a
  533. Else
  534. Pick = b
  535. End If
  536. End Function
  537. Function GetAppSetting(key, configFilePath)
  538. Dim xml, nodes, node, j
  539. If Not fso.FileExists(configFilePath) Then
  540. GetAppSetting = "nothing"
  541. Exit Function
  542. End If
  543. Set xml = CreateObject("Microsoft.XMLDOM")
  544. xml.Async = False
  545. xml.Load(configFilePath)
  546. Set nodes = xml.selectNodes("//appSettings/add")
  547. For j = 0 To nodes.Length - 1
  548. Set node = nodes.Item(j)
  549. If node.getAttribute("key") = key Then
  550. GetAppSetting = node.getAttribute("value")
  551. Exit Function
  552. End If
  553. Next
  554. GetAppSetting = "nothing"
  555. End Function
  556. Function StrEqualCI(a, b)
  557. StrEqualCI = (LCase(CStr(a)) = LCase(CStr(b)))
  558. End Function
  559. Function IsValidIdentifier(name)
  560. Dim n, ch
  561. IsValidIdentifier = False
  562. If Len(name) = 0 Then Exit Function
  563. For n = 1 To Len(name)
  564. ch = Mid(name, n, 1)
  565. If Not ((ch >= "a" And ch <= "z") Or (ch >= "A" And ch <= "Z") Or (ch >= "0" And ch <= "9") Or ch = "_") Then Exit Function
  566. Next
  567. IsValidIdentifier = True
  568. End Function

Powered by TurnKey Linux.