> To fix this to work with threads you should use a threadvar, and initialise 
> the DB connection in each thread.

Ah, but that gets me back to 2 seconds delay per page.

Just for fun; started diving in. I created a new element called `decorate`:
    
    
    decorate <name>:
      beforeThread <identifier>, <type>:
        # causes a COPY of identifier to be passed as a parameter to the route.
      beforeRoutes:
        # statements to run prior to running the code in any route
        # this is different than "before:" (as found in routers) because any 
variables here
        # are still in context for the route itself.
      afterRoutes:
        # statements to run immediately after running the code in any route
        # used for cleanup such as saving cookies etc.
      afterThread:
        # in the same context as 'beforeThread'. Meant for cleanup after the 
async thread has closed.
    
    
    Run

The decorators are setup to be chainable. In fact, if someone wrote templates, 
one could add functionality to `jester` with stuff like:
    
    
    jesterUserManagement()
    jesterTrafficLogger()
    
    
    Run

Here is an example of `decorate` I am testing:
    
    
    import jester, sequtils
    
    type
      fakePoolEntry = tuple
        id: int
        free: bool
    
    var fakePool: seq[fakePoolEntry] = @[]
    for i in 0 .. 9:
      fakePool.add (id: i, free: true)
    var tryNext = 0
    
    proc getOne(): fakePoolEntry =
      for i in 0 .. 9:
        tryNext = (tryNext + 1) mod 10
        if fakePool[tryNext].free:
          fakePool[tryNext].free = false
          result = fakePool[tryNext]
          break
    
    proc returnOne(db: fakePoolEntry) =
      for i in 0 .. 9:
        if fakePool[i].id == db.id:
          fakePool[i].free = true
    
    decorate helloWorld:
      beforeThread db, fakePoolEntry:
        var db = getOne()
      beforeRoutes:
        var name = "Joe"
        var something = 3
      afterRoutes:
        echo "something = ", something
      afterThread:
        returnOne(db)
    
    routes:
      get "/":
        something = 2
        resp "hello, " & name & " pool number =" & $db.id
    
    
    Run

It kind-of-sort-of works. It does what it says, but the underlying 
`asynchttpserver` is _also_ running threads. So the `asynchttpserver` complains 
about `beforeThread` accessing global memory, but not the async call to the 
route is okay.

Will play with it some more...

Reply via email to