'============================================================== ' GenerateApi.vbs (AxonASP CLI + G3DB edition) ' ' Usage (runs under the AxonASP CLI in the container; gen.cmd runs GenerateRepo.vbs first): ' scripts\gen.cmd api /table:Products /pk:Id ' ' Sets up a JSON API for one table: ' app/controllers/ApiController.asp controller (list/search/paging, show, create, PUT, PATCH, delete) ' app/controllers/autoload_controllers.asp include line added ' app/models/autoload_models.asp POBO + repository include lines added ' core/lib.ControllerRegistry.asp controller whitelisted ' public/Default.asp 6 routes under /api/
added ' public/api/
.openapi.json OpenAPI spec (shows up in the /api/docs Swagger UI) ' api-tests/
.http sample requests (VS Code REST Client) ' ' Notes: a JSON null is not accepted for a field (omit it instead). Needs app/models/POBO_
.asp and
Repository.asp (GenerateRepo.vbs). Refuses to overwrite an ' existing controller. Validation is derived from the column types and NOT NULL / DEFAULT; add business rules ' (ranges, lengths) in the generated controller by hand. '============================================================== Option Explicit ' AxonASP CLI: provide the WScript object (see _cli.vbs) Dim shimFso Set shimFso = CreateObject("Scripting.FileSystemObject") ExecuteGlobal shimFso.OpenTextFile(Server.MapPath("/scripts/_cli.vbs"), 1).ReadAll Dim fso, args, i, arg, parts, tableName, primaryKey, csKey, configPath Set fso = CreateObject("Scripting.FileSystemObject") Set args = WScript.Arguments csKey = "ConnectionString" configPath = Server.MapPath("/public/web.config") For i = 0 To args.Count - 1 arg = args(i) If InStr(arg, ":") > 0 Then parts = Split(arg, ":", 2) Select Case LCase(Replace(parts(0), "/", "")) Case "table": tableName = parts(1) Case "pk": primaryKey = parts(1) End Select End If Next If Len(tableName) = 0 Or Len(primaryKey) = 0 Then WScript.Echo "Usage: scripts\gen.cmd api /table: /pk:" WScript.Quit 1 End If If Not IsValidIdentifier(tableName) Or Not IsValidIdentifier(primaryKey) Then WScript.Echo "Error: table and primary key may only contain letters, numbers and underscores." WScript.Quit 1 End If Dim ctrlPath, routeName, constName routeName = LCase(tableName) constName = "API_" & UCase(tableName) ctrlPath = Server.MapPath("/app/controllers/Api" & tableName & "Controller.asp") If fso.FileExists(ctrlPath) Then WScript.Echo "Error: " & ctrlPath & " already exists. Delete it first if you want to regenerate." WScript.Quit 1 End If If Not fso.FileExists(Server.MapPath("/app/models/" & tableName & "Repository.asp")) Then WScript.Echo "Error: app/models/" & tableName & "Repository.asp not found. Run: scripts\gen.cmd repo /table:" & tableName & " /pk:" & primaryKey WScript.Quit 1 End If '---------------- Connection + schema ---------------- Dim connStr, p, dsn, db connStr = GetAppSetting(csKey, configPath) p = InStr(connStr, ":") If connStr = "nothing" Or p < 2 Then WScript.Echo "Error: ConnectionString not found or malformed in " & configPath WScript.Quit 1 End If If LCase(Left(connStr, p - 1)) <> "sqlite" Then WScript.Echo "Error: schema discovery is implemented for SQLite only." WScript.Quit 1 End If dsn = Mid(connStr, p + 1) Set db = Server.CreateObject("G3DB") If Not db.Open("sqlite", dsn) Then WScript.Echo "DB connection failed: " & db.LastError WScript.Quit 1 End If ' cols(i) name, kinds(i) string|int|real|bool|date, needs(i) True when NOT NULL without DEFAULT, isPk(i) Dim cols(), kinds(), needs(), isPk(), dflts(), idx, rs, declType, notNull, dflt, pkFlag idx = -1 Set rs = db.Query("PRAGMA table_info(" & tableName & ")") If IsEmpty(rs) Then WScript.Echo "Error reading table [" & tableName & "]: " & db.LastError WScript.Quit 1 End If Do Until rs.EOF idx = idx + 1 ReDim Preserve cols(idx), kinds(idx), needs(idx), isPk(idx), dflts(idx) cols(idx) = CStr(rs(1)) declType = "" & rs(2) notNull = rs(3) dflt = rs(4) dflts(idx) = dflt pkFlag = rs(5) kinds(idx) = ApiKind(declType) isPk(idx) = (StrEqualCI(cols(idx), primaryKey) Or CLng(pkFlag) > 0) needs(idx) = (CLng(notNull) = 1 And IsNull(dflt) And Not isPk(idx)) rs.MoveNext Loop rs.Close db.Close If idx < 0 Then WScript.Echo "No columns found for table [" & tableName & "]. Run the migrations first." WScript.Quit 1 End If '---------------- Build the pieces ---------------- Dim newDefaults, updStamps, dv, members, clearFields, parseBody, applyBody, rowJson, docFields, searchCols, orderCol, writable newDefaults = "" : updStamps = "" : members = "" : clearFields = "" : parseBody = "" : applyBody = "" : rowJson = "" : docFields = "" : searchCols = "" : orderCol = primaryKey writable = 0 Dim q q = Chr(34) For i = 0 To idx Dim c, camel, fv c = cols(i) camel = LCase(Left(c, 1)) & Mid(c, 2) fv = "f_" & c ' ---- output JSON (all columns) If Len(rowJson) = 0 Then rowJson = q & "{" & q & q & camel & q & q & ":" & q & " & " & JsonExpr(c, kinds(i), isPk(i)) Else rowJson = rowJson & " & _" & vbCrLf & " " & q & "," & q & q & camel & q & q & ":" & q & " & " & JsonExpr(c, kinds(i), isPk(i)) End If ' ---- first string column is the default sort, string columns are searchable If kinds(i) = "string" And Not isPk(i) Then If Len(searchCols) > 0 Then searchCols = searchCols & ", " searchCols = searchCols & """" & c & """" If orderCol = primaryKey Then orderCol = c End If If isPk(i) Then docFields = docFields & "' " & camel & " (read-only primary key)" & vbCrLf ElseIf IsStampCol(c, kinds(i)) Then ' CreatedAt / UpdatedAt are managed by the server If LCase(c) = "createdat" Then newDefaults = newDefaults & " rec." & c & " = NowStamp()" & vbCrLf Else newDefaults = newDefaults & " rec." & c & " = NowStamp()" & vbCrLf updStamps = updStamps & " rec." & c & " = NowStamp()" & vbCrLf End If docFields = docFields & "' " & camel & " (set by the server)" & vbCrLf Else writable = writable + 1 dv = DefaultLiteral(dflts(i)) If Len(dv) > 0 Then newDefaults = newDefaults & " rec." & c & " = " & dv & vbCrLf End If members = members & " Private " & fv & vbCrLf clearFields = clearFields & " " & fv & " = Empty" & vbCrLf parseBody = parseBody & BuildParse(c, camel, fv, kinds(i), needs(i)) applyBody = applyBody & " If Not IsEmpty(" & fv & ") Then" & vbCrLf & _ " rec." & c & " = " & fv & vbCrLf & _ " End If" & vbCrLf docFields = docFields & "' " & c & " (" & kinds(i) & Pick(needs(i), ", required", "") & ")" & vbCrLf End If Next rowJson = rowJson & " & ""}""" If Len(searchCols) = 0 Then searchCols = "Empty" Else searchCols = "Array(" & searchCols & ")" End If docFields = Left(docFields, Len(docFields) - 2) '---------------- Write the controller ---------------- Dim t t = ReadTemplate("Api.tpl.asp") t = Replace(t, "{{TABLE}}", tableName) t = Replace(t, "{{PK}}", primaryKey) t = Replace(t, "{{ROUTE}}", routeName) t = Replace(t, "{{CONST}}", constName) If Len(updStamps) = 0 Then t = Replace(t, "{{UPDATE_STAMPS}}" & vbLf, "") t = Replace(t, "{{UPDATE_STAMPS}}" & vbCrLf, "") Else t = Replace(t, "{{UPDATE_STAMPS}}", Left(updStamps, Len(updStamps) - 2)) End If If Len(newDefaults) = 0 Then t = Replace(t, "{{NEW_DEFAULTS}}" & vbCrLf, "") Else t = Replace(t, "{{NEW_DEFAULTS}}", Left(newDefaults, Len(newDefaults) - 2)) End If t = Replace(t, "{{DATE}}", CStr(Now())) t = Replace(t, "{{DOC_FIELDS}}", docFields) t = Replace(t, "{{MEMBERS}}", Left(members, Len(members) - 2)) t = Replace(t, "{{CLEAR_FIELDS}}", Left(clearFields, Len(clearFields) - 2)) t = Replace(t, "{{PARSE_BODY}}", parseBody) t = Replace(t, "{{APPLY_BODY}}", Left(applyBody, Len(applyBody) - 2)) t = Replace(t, "{{SEARCH_COLS}}", searchCols) t = Replace(t, "{{ORDER_COL}}", orderCol) t = Replace(t, "{{ROW_JSON}}", rowJson) WriteFile ctrlPath, t WScript.Echo "Controller: " & ctrlPath '---------------- Wire it up ---------------- AppendIfMissing "/app/models/autoload_models.asp", "POBO_" & tableName & ".asp", "" AppendIfMissing "/app/models/autoload_models.asp", tableName & "Repository.asp", "" AppendIfMissing "/app/controllers/autoload_controllers.asp", "Api" & tableName & "Controller.asp", "" WScript.Echo "Includes: autoload_models.asp, autoload_controllers.asp" InsertAfterLine "/core/lib.ControllerRegistry.asp", "RegisterController ""errorcontroller""", "api" & LCase(tableName) & "controller", _ " RegisterController ""api" & LCase(tableName) & "controller""" WScript.Echo "Registry: api" & LCase(tableName) & "controller whitelisted" Dim r r = vbTab & "' " & tableName & " JSON API (generated by GenerateApi.vbs)" & vbCrLf & _ vbTab & "router.AddRoute ""GET"", ""/api/" & routeName & """, ""Api" & tableName & "Controller"", ""Index""" & vbCrLf & _ vbTab & "router.AddRoute ""POST"", ""/api/" & routeName & """, ""Api" & tableName & "Controller"", ""Create""" & vbCrLf & _ vbTab & "router.AddRoute ""GET"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Show""" & vbCrLf & _ vbTab & "router.AddRoute ""PUT"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Update""" & vbCrLf & _ vbTab & "router.AddRoute ""PATCH"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Update""" & vbCrLf & _ vbTab & "router.AddRoute ""DELETE"", ""/api/" & routeName & "/:id"", ""Api" & tableName & "Controller"", ""Delete""" & vbCrLf & vbCrLf InsertBeforeLine "/public/Default.asp", "' Dispatch the request", "Api" & tableName & "Controller", r WScript.Echo "Routes: /api/" & routeName & " and /api/" & routeName & "/:id added to public/Default.asp" '---------------- Spec + sample requests ---------------- Dim specDir, specPath specDir = Server.MapPath("/public/api") If Not fso.FolderExists(specDir) Then fso.CreateFolder specDir specPath = specDir & "/" & routeName & ".openapi.json" WriteFile specPath, BuildSpec() WScript.Echo "OpenAPI spec: " & specPath Dim httpDir, httpPath httpDir = Server.MapPath("/api-tests") If Not fso.FolderExists(httpDir) Then fso.CreateFolder httpDir httpPath = httpDir & "/" & routeName & ".http" WriteFile httpPath, BuildHttp() WScript.Echo "Sample calls: " & httpPath WScript.Echo "" WScript.Echo "Done. Restart the container (docker restart axonasp), then open /api/docs and pick '" & tableName & "' in the spec list." '============================================================== ' Code generation '============================================================== Function BuildParse(c, camel, fv, kind, required) Dim s, label label = c s = " k = """"" & vbCrLf s = s & " If input.Exists(""" & c & """) Then" & vbCrLf s = s & " k = """ & c & """" & vbCrLf If camel <> c Then s = s & " ElseIf input.Exists(""" & camel & """) Then" & vbCrLf s = s & " k = """ & camel & """" & vbCrLf End If s = s & " End If" & vbCrLf s = s & " If Len(k) > 0 Then" & vbCrLf s = s & " v = input.Item(k)" & vbCrLf Select Case kind Case "string" s = s & " v = Trim("""" & v)" & vbCrLf If required Then s = s & " If Len(v) = 0 Then" & vbCrLf s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " is required.""" & vbCrLf s = s & " End If" & vbCrLf End If s = s & " " & fv & " = v" & vbCrLf Case "int", "real" s = s & " If VarType(v) = 11 Then" & vbCrLf s = s & " v = CLng(v) * -1" & vbCrLf s = s & " End If" & vbCrLf s = s & " If IsNumeric(v) And Not IsNull(v) And VarType(v) <> 8 Then" & vbCrLf If kind = "int" Then s = s & " If CDbl(v) <> Int(CDbl(v)) Then" & vbCrLf s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a whole number.""" & vbCrLf s = s & " Else" & vbCrLf s = s & " " & fv & " = CLng(v)" & vbCrLf s = s & " End If" & vbCrLf Else s = s & " " & fv & " = CDbl(v)" & vbCrLf End If s = s & " Else" & vbCrLf s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a number.""" & vbCrLf s = s & " End If" & vbCrLf Case "bool" s = s & " If VarType(v) = 11 Then" & vbCrLf s = s & " " & fv & " = v" & vbCrLf s = s & " ElseIf IsNumeric(v) And Not IsNull(v) And VarType(v) <> 8 Then" & vbCrLf s = s & " " & fv & " = (CDbl(v) <> 0)" & vbCrLf s = s & " Else" & vbCrLf s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be true or false.""" & vbCrLf s = s & " End If" & vbCrLf Case "date" s = s & " If IsDate(v) Then" & vbCrLf s = s & " " & fv & " = CDate(v)" & vbCrLf s = s & " Else" & vbCrLf s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " must be a date.""" & vbCrLf s = s & " End If" & vbCrLf End Select If required Then s = s & " ElseIf Not partial Then" & vbCrLf s = s & " n = n + 1 : ReDim Preserve errs(n) : errs(n) = """ & c & " is required.""" & vbCrLf End If s = s & " End If" & vbCrLf & vbCrLf BuildParse = s End Function ' VBScript expression (generator output) that renders column c of "rec" as a JSON value Function JsonExpr(c, kind, pk) If pk Or kind = "int" Then JsonExpr = "CLng(rec." & c & ")" ElseIf kind = "real" Then JsonExpr = "JsonLite_Num(rec." & c & ")" ElseIf kind = "bool" Then JsonExpr = "LCase(CStr(CBool(rec." & c & ")))" ElseIf kind = "date" Then JsonExpr = "JsonDate(rec." & c & ")" Else JsonExpr = "JsonLite_Quote(rec." & c & ")" End If End Function Function BuildSpec() Dim sch, inp, req, k, nm, ty, ex, exs, sep sch = "" : inp = "" : req = "" : exs = "" For k = 0 To idx nm = LCase(Left(cols(k), 1)) & Mid(cols(k), 2) ty = SpecType(kinds(k), isPk(k)) If Len(sch) > 0 Then sch = sch & "," & vbCrLf sch = sch & " """ & nm & """: " & ty If Not isPk(k) And Not IsStampCol(cols(k), kinds(k)) Then If Len(inp) > 0 Then inp = inp & "," & vbCrLf inp = inp & " """ & cols(k) & """: " & ty If needs(k) Then If Len(req) > 0 Then req = req & ", " req = req & """" & cols(k) & """" End If If Len(exs) > 0 Then exs = exs & ", " exs = exs & """" & cols(k) & """: " & SampleValue(kinds(k)) End If Next Dim reqLine reqLine = "" If Len(req) > 0 Then reqLine = " ""required"": [" & req & "]," & vbCrLf Dim T, R T = tableName : R = routeName Dim s s = "{" & vbCrLf s = s & " ""openapi"": ""3.0.3""," & vbCrLf 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 s = s & " ""servers"": [{ ""url"": ""/"" }]," & vbCrLf s = s & " ""tags"": [{ ""name"": """ & T & """ }]," & vbCrLf s = s & " ""paths"": {" & vbCrLf s = s & " ""/api/" & R & """: {" & vbCrLf s = s & " ""get"": { ""tags"": [""" & T & """], ""summary"": ""List (search + paging)""," & vbCrLf s = s & " ""parameters"": [" & vbCrLf s = s & " { ""name"": ""q"", ""in"": ""query"", ""schema"": { ""type"": ""string"" }, ""description"": ""Case-insensitive match on the text columns"" }," & vbCrLf s = s & " { ""name"": ""page"", ""in"": ""query"", ""schema"": { ""type"": ""integer"", ""minimum"": 1, ""default"": 1 } }," & vbCrLf s = s & " { ""name"": ""per_page"", ""in"": ""query"", ""schema"": { ""type"": ""integer"", ""minimum"": 1, ""maximum"": 100, ""default"": 10 } }" & vbCrLf s = s & " ]," & vbCrLf s = s & " ""responses"": { ""200"": { ""description"": ""A page of records"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/List"" } } } } } }," & vbCrLf s = s & " ""post"": { ""tags"": [""" & T & """], ""summary"": ""Create""," & vbCrLf s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {" & exs & "} } } }," & vbCrLf 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 s = s & " }," & vbCrLf s = s & " ""/api/" & R & "/{id}"": {" & vbCrLf s = s & " ""parameters"": [{ ""name"": ""id"", ""in"": ""path"", ""required"": true, ""schema"": { ""type"": ""integer"" } }]," & vbCrLf s = s & " ""get"": { ""tags"": [""" & T & """], ""summary"": ""Get one""," & vbCrLf s = s & " ""responses"": { ""200"": { ""description"": ""The record"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Envelope"" } } } }, ""404"": { ""$ref"": ""#/components/responses/Error"" } } }," & vbCrLf s = s & " ""put"": { ""tags"": [""" & T & """], ""summary"": ""Replace (required fields enforced)""," & vbCrLf s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {" & exs & "} } } }," & vbCrLf 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 s = s & " ""patch"": { ""tags"": [""" & T & """], ""summary"": ""Partial update (only fields sent change)""," & vbCrLf s = s & " ""requestBody"": { ""required"": true, ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Input"" }, ""example"": {} } } }," & vbCrLf 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 s = s & " ""delete"": { ""tags"": [""" & T & """], ""summary"": ""Delete""," & vbCrLf 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 s = s & " }" & vbCrLf s = s & " }," & vbCrLf s = s & " ""components"": {" & vbCrLf s = s & " ""schemas"": {" & vbCrLf s = s & " ""Record"": { ""type"": ""object"", ""properties"": {" & vbCrLf & sch & vbCrLf & " } }," & vbCrLf s = s & " ""Input"": { ""type"": ""object""," & vbCrLf & reqLine & " ""properties"": {" & vbCrLf & inp & vbCrLf & " } }," & vbCrLf s = s & " ""Envelope"": { ""type"": ""object"", ""properties"": { ""data"": { ""$ref"": ""#/components/schemas/Record"" } } }," & vbCrLf 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 s = s & " ""Error"": { ""type"": ""object"", ""properties"": { ""error"": { ""type"": ""object"", ""properties"": { ""message"": { ""type"": ""string"" }, ""details"": { ""type"": ""array"", ""items"": { ""type"": ""string"" } } } } } }" & vbCrLf s = s & " }," & vbCrLf s = s & " ""responses"": { ""Error"": { ""description"": ""Error"", ""content"": { ""application/json"": { ""schema"": { ""$ref"": ""#/components/schemas/Error"" } } } } }" & vbCrLf s = s & " }" & vbCrLf s = s & "}" & vbCrLf BuildSpec = s End Function Function BuildHttp() Dim k, ex, h ex = "" For k = 0 To idx If Not isPk(k) And Not IsStampCol(cols(k), kinds(k)) Then If Len(ex) > 0 Then ex = ex & ", " ex = ex & """" & cols(k) & """: " & SampleValue(kinds(k)) End If Next h = "### " & tableName & " JSON API. Use with the VS Code ""REST Client"" extension (or any .http runner)." & vbLf h = h & "@base = http://localhost:8801" & vbLf & vbLf h = h & "### List (q = text search, page, per_page max 100)" & vbLf & "GET {{base}}/api/" & routeName & "?page=1&per_page=5" & vbLf & vbLf h = h & "### Show" & vbLf & "GET {{base}}/api/" & routeName & "/1" & vbLf & vbLf h = h & "### Create -> 201 + Location header" & vbLf & "POST {{base}}/api/" & routeName & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ " & ex & " }" & vbLf & vbLf h = h & "### Replace (required fields enforced)" & vbLf & "PUT {{base}}/api/" & routeName & "/1" & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ " & ex & " }" & vbLf & vbLf h = h & "### Partial update (only the fields sent change)" & vbLf & "PATCH {{base}}/api/" & routeName & "/1" & vbLf & "Content-Type: application/json" & vbLf & vbLf & "{ }" & vbLf & vbLf h = h & "### Delete" & vbLf & "DELETE {{base}}/api/" & routeName & "/1" & vbLf BuildHttp = h End Function Function SpecType(kind, pk) If pk Or kind = "int" Then SpecType = "{ ""type"": ""integer"" }" ElseIf kind = "real" Then SpecType = "{ ""type"": ""number"" }" ElseIf kind = "bool" Then SpecType = "{ ""type"": ""boolean"" }" ElseIf kind = "date" Then SpecType = "{ ""type"": ""string"", ""format"": ""date-time"", ""nullable"": true }" Else SpecType = "{ ""type"": ""string"" }" End If End Function ' SQLite DEFAULT text -> VBScript literal ("" when it is not a plain number or quoted string) Function DefaultLiteral(d) Dim s DefaultLiteral = "" If IsNull(d) Then Exit Function s = Trim("" & d) If Len(s) = 0 Then Exit Function If IsNumeric(s) Then DefaultLiteral = s ElseIf Len(s) >= 2 And Left(s, 1) = "'" And Right(s, 1) = "'" Then s = Mid(s, 2, Len(s) - 2) DefaultLiteral = """" & Replace(Replace(s, "''", "'"), """", """""") & """" End If End Function Function SampleValue(kind) Select Case kind Case "int": SampleValue = "1" Case "real": SampleValue = "9.99" Case "bool": SampleValue = "true" Case "date": SampleValue = """2026-01-01 00:00:00""" Case Else: SampleValue = """text""" End Select End Function '============================================================== ' File helpers '============================================================== Function ReadTemplate(name) Dim ts Set ts = fso.OpenTextFile(Server.MapPath("/scripts/templates/" & name), 1) ReadTemplate = ts.ReadAll ts.Close End Function Function ReadFile(path) Dim ts Set ts = fso.OpenTextFile(Server.MapPath(path), 1) ReadFile = ts.ReadAll ts.Close End Function Sub WriteFile(path, text) Dim tf Set tf = fso.CreateTextFile(path, True) tf.Write text tf.Close End Sub Function EolOf(text) If InStr(text, vbCrLf) > 0 Then EolOf = vbCrLf Else EolOf = vbLf End If End Function Function WithEol(text, eol) WithEol = Replace(Replace(text, vbCrLf, vbLf), vbLf, eol) End Function ' Appends a line to the file unless "marker" is already in it Sub AppendIfMissing(path, marker, line) Dim s, eol s = ReadFile(path) If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub eol = EolOf(s) If Right(s, 1) <> vbLf Then s = s & eol WriteFile Server.MapPath(path), s & line & eol End Sub ' Inserts newText on a new line after the first line containing anchor (unless marker is already present) Sub InsertAfterLine(path, anchor, marker, newText) Dim s, eol, pos, eolPos s = ReadFile(path) If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub eol = EolOf(s) pos = InStr(1, s, anchor, vbTextCompare) If pos = 0 Then WScript.Echo "Warning: anchor '" & anchor & "' not found in " & path & "; add the line yourself: " & newText Exit Sub End If eolPos = InStr(pos, s, eol) s = Left(s, eolPos - 1) & eol & newText & Mid(s, eolPos) WriteFile Server.MapPath(path), s End Sub ' Inserts newText before the line containing anchor (unless marker is already present) Sub InsertBeforeLine(path, anchor, marker, newText) Dim s, eol, pos, lineStart s = ReadFile(path) If InStr(1, s, marker, vbTextCompare) > 0 Then Exit Sub eol = EolOf(s) pos = InStr(1, s, anchor, vbTextCompare) If pos = 0 Then WScript.Echo "Warning: anchor '" & anchor & "' not found in " & path & "; add the routes yourself:" & vbCrLf & newText Exit Sub End If lineStart = InStrRev(s, eol, pos) If lineStart = 0 Then lineStart = 1 Else lineStart = lineStart + Len(eol) End If s = Left(s, lineStart - 1) & WithEol(newText, eol) & Mid(s, lineStart) WriteFile Server.MapPath(path), s End Sub '============================================================== ' Misc helpers '============================================================== ' SQLite declared type -> string | int | real | bool | date Function ApiKind(declType) Dim t t = UCase("" & declType) If InStr(t, "BOOL") > 0 Then ApiKind = "bool" ElseIf InStr(t, "DATE") > 0 Or InStr(t, "TIME") > 0 Then ApiKind = "date" ElseIf InStr(t, "CHAR") > 0 Or InStr(t, "CLOB") > 0 Or InStr(t, "TEXT") > 0 Then ApiKind = "string" ElseIf InStr(t, "INT") > 0 Then ApiKind = "int" 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 ApiKind = "real" Else ApiKind = "string" End If End Function ' CreatedAt / UpdatedAt text or date columns are filled in by the server, not accepted from clients Function IsStampCol(name, kind) IsStampCol = False If kind = "string" Or kind = "date" Then If LCase(name) = "createdat" Or LCase(name) = "updatedat" Then IsStampCol = True End If End Function Function Pick(cond, a, b) If cond Then Pick = a Else Pick = b End If End Function Function GetAppSetting(key, configFilePath) Dim xml, nodes, node, j If Not fso.FileExists(configFilePath) Then GetAppSetting = "nothing" Exit Function End If Set xml = CreateObject("Microsoft.XMLDOM") xml.Async = False xml.Load(configFilePath) Set nodes = xml.selectNodes("//appSettings/add") For j = 0 To nodes.Length - 1 Set node = nodes.Item(j) If node.getAttribute("key") = key Then GetAppSetting = node.getAttribute("value") Exit Function End If Next GetAppSetting = "nothing" End Function Function StrEqualCI(a, b) StrEqualCI = (LCase(CStr(a)) = LCase(CStr(b))) End Function Function IsValidIdentifier(name) Dim n, ch IsValidIdentifier = False If Len(name) = 0 Then Exit Function For n = 1 To Len(name) ch = Mid(name, n, 1) If Not ((ch >= "a" And ch <= "z") Or (ch >= "A" And ch <= "Z") Or (ch >= "0" And ch <= "9") Or ch = "_") Then Exit Function Next IsValidIdentifier = True End Function