Pradeep's Stream

Adding /export endpoint to tohray

I added the /export endpoint to tohray. This allows the user to backup the whole blog in either JSON on Markdown format.

A GET call to /export returns JSON (default format). And user can get all the posts in markdown format by attaching ?format=md to the above endpoint, ie., /export?format=md.

Added to urls.nim:

pattern("/export", exportAll, HttpGet, name="export"),

Added to views.nim:

proc exportAll*(ctx: Context) {.async.} =
  let
    format = ctx.getQueryParams("format", "json")
    db = open(consts.dbPath, "", "", "")
    rows = db.getAllRows(sql"SELECT slug, created, content FROM post ORDER BY created DESC")
  defer: db.close()
  if format == "json":
    ctx.response.addHeader("Content-Type", "application/json")
    var jsonArray = newJArray()
    for row in rows:
        var jsonObject = %*{
          "slug": row[0],
          "created": row[1],
          "content": row[2]
        }
        jsonArray.add(jsonObject)
    resp jsonResponse(%*{"posts": jsonArray})
  elif format == "md":
    ctx.response.addHeader("Content-Type", "text/plain")
    var res:string
    for row in rows:
      res = res & "\n" & row[0] & "\n" &  row[1] & "\n\n" & $rows[2] & "\n\n" & chr(28) # ascii file separator
    resp res
Calendar , Export