Search code examples
hookloopbackjsconnector

What is the difference between ctx.end() and next()?


I'm trying to figure out the difference between next() and ctx.end() in connector hooks of loopback.

Moreover, why the ctx.end() function cannot be used for other hooks?

Thanks for your help !


Solution

  • After digging a while :

    • First, next() and ctx.end() do share the same signature.

    • If several observers are bound to the connector, they are called one after the other (by order of binding).

      • Calling next() calls the next observer
      • Calling ctx.end() ends "closes" the event

    Example-1 (coffee) :

    connectorName.connector.observe 'after execute', (ctx, next) ->
        console.log "hook1", new Date()
        wait(3000)
        ctx.end null, ctx, ctx.res.body
    connectorName.connector.observe 'after execute', (ctx, next) ->
        console.log "hook2", new Date()
        wait(3000)
        next()
    

    Example-2 (coffee) :

    connectorName.connector.observe 'after execute', (ctx, next) ->
        console.log "hook1", new Date()
        wait(3000);
        next null, ctx, ctx.res.body
    connectorName.connector.observe 'after execute', (ctx, next) ->
        console.log "hook2", new Date()
        wait(3000)
        next()
    

    In the first example, the second hook is never called. In the second it is normally called.

    pgConnector.connector.observe 'after execute', (ctx, next) ->
        console.log "hook2", new Date()
        wait(3000);
        ctx.end(null, ctx.res)
    
    pgConnector.connector.observe 'after execute', (ctx, next) ->
        console.log "hook3", new Date()
        wait(3000);
        next()
    

    Same here with database connector.