diff --git a/src/plugins/edge.ts b/src/plugins/edge.ts index 157be41..1c1497f 100644 --- a/src/plugins/edge.ts +++ b/src/plugins/edge.ts @@ -190,4 +190,54 @@ export const edgePluginSession: PluginFn = (edge) => { buffer.writeStatement(`}`, token.filename, token.loc.start.line) }, }) + + edge.registerTag({ + tagName: 'errors', + seekable: true, + block: true, + compile(parser, buffer, token) { + /** + * Write an if statement + */ + buffer.writeStatement( + `if (state.flashMessages.has('errorsBag')) {`, + token.filename, + token.loc.start.line + ) + + /** + * Define a local variable + */ + buffer.writeExpression( + `let $messages = state.flashMessages.get('errorsBag')`, + token.filename, + token.loc.start.line + ) + + /** + * Create a local variables scope and tell the parser about + * the existence of the "messages" variable + */ + parser.stack.defineScope() + parser.stack.defineVariable('$messages') + + /** + * Process component children using the parser + */ + token.children.forEach((child) => { + parser.processToken(child, buffer) + }) + + /** + * Clear the scope of the local variables before we + * close the if statement + */ + parser.stack.clearScope() + + /** + * Close if statement + */ + buffer.writeStatement(`}`, token.filename, token.loc.start.line) + }, + }) } diff --git a/tests/session.spec.ts b/tests/session.spec.ts index b5fae14..745440b 100644 --- a/tests/session.spec.ts +++ b/tests/session.spec.ts @@ -1419,4 +1419,60 @@ test.group('Session | Flash', (group) => { ['

Access denied

', ''] ) }) + + test('access errorsBag using the @errors tag', async ({ assert }) => { + let sessionId: string | undefined + + edge.registerTemplate('flash_errors_messages', { + template: ` + @errors() +
+ @each(message in $messages) +

{{ message }}

+ @end +
+ @else +

No error messages

+ @end + `, + }) + + const server = httpServer.create(async (req, res) => { + const request = new RequestFactory().merge({ req, res, encryption }).create() + const response = new ResponseFactory().merge({ req, res, encryption }).create() + const ctx = new HttpContextFactory().merge({ request, response }).create() + + const session = new Session(sessionConfig, cookieDriver, emitter, ctx) + await session.initiate(false) + sessionId = session.sessionId + + if (request.url() === '/prg') { + response.send(await ctx.view.render('flash_errors_messages')) + await session.commit() + response.finish() + } else { + session.flashErrors({ + E_ACCESS_DENIED: 'Access denied', + }) + await session.commit() + } + + response.finish() + }) + + const { headers } = await supertest(server).get('/') + const cookies = setCookieParser.parse(headers['set-cookie'], { map: true }) + + const { text } = await supertest(server) + .get('/prg') + .set( + 'Cookie', + `adonis_session=${cookies.adonis_session.value}; ${sessionId}=${cookies[sessionId!].value}` + ) + + assert.deepEqual( + text.split('\n').map((line) => line.trim()), + ['
', '

Access denied

', '
', ''] + ) + }) })