So I'm trying to get a small web service up and running with Jester, but there are no proper examples that show a step-by-step method for an actual application that works with a DB and does GET and POST requests to get, post, update and delete things from a DB.
Hence, this is my attempt at both learning and providing such an example/s.
This is the code I have so far written:
import jester, asyncdispatch, htmlgen, db_sqlite, parseutils, strutils, times, templates
proc openDatabase(path: string): DbConn =
## Creates or opens the sqlite3 database.
##
## Pass the path to the sqlite database, if the database doesn't exist it
## will be created. The proc may raise a EDB exception
let
conn = db_sqlite.open(path, "user", "pass", "db")
query = sql"""CREATE TABLE IF NOT EXISTS Todos (
id INTEGER PRIMARY KEY,
priority INTEGER NOT NULL,
is_done BOOLEAN NOT NULL,
desc TEXT NOT NULL,
modification_date INTEGER NOT NULL,
CONSTRAINT Todos UNIQUE (id))"""
db_sqlite.exec(conn, query)
result = conn
proc view(obj: Todo): string = tmpli html"""
<ul>
$for item in obj {
<li>$item</li>
}
</ul>
"""
proc getTodo(conn: DbConnection, id: string): string =
var todo = Todo(id: id)
if conn.update(todo):
return view(todo)
return tmpli html"""
<h1>Failed to update</h1>
"""
routes:
get "/@id":
resp getTodo(myConn, @"id")
runForever()
Most of the code so far is stuff I have found from other examples (my first goal is to get a basic GET request running).
I can't understand how the DB is interacting with the other procs though (unless I haven't implemented that yet?)
Is there any way to replicate the way Flask does things (separating into a model.nim, con.nim and view.nim) with some type of Jinja2-ish integration in view.nim .
Also, is my DB specified correctly?
You can look at Nimrod Forum code as an example of using both Jester and SQLite.
Edit
There's more up-to-date new_async branch, it's compiled with current compiler (devel) and new_async branch of Jester.
Is there no simpler example except the nimforum site?
I want to build out a set of examples that show Jesters use for building micro-services, but the lack of examples is holding me back (it is a case of catch-22, where I need a solid starter example to make moor-moor of them)
Just save your 'conn' sql connection as a global variable or else you have to pass around some sort of 'context' which has a reference to your connection.
i.e.
var conn: DbConnection
proc setupConnection() =
conn = someDbConnectionInitializationHere....
routes:
... use 'conn' here.
proc initialize() =
setupConnection()
runForever()
var conn: DbConnection
Throws up an error in the compiler.
I assumed DbConnection was an identifier (or linked to a library possibly)?
the error I get is:
Error: undeclared identifier: 'DbConnection'
Is this the right type for var conn ?