Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Last active April 4, 2018 11:43
Show Gist options
  • Save Sleavely/da1ac50e1ea614b4171beae7868ec3ed to your computer and use it in GitHub Desktop.
Save Sleavely/da1ac50e1ea614b4171beae7868ec3ed to your computer and use it in GitHub Desktop.
A middleware for automatically converting AdonisJS responses to JSONP

JsonpDetector middleware

A simplistic approach to automatically converting responses to JSONP, since Adonis does not do this for you.

Compatible with Adonis 4.1

Installing

  1. adonis make:middleware JsonpDetector
  2. In start/kernel.js, add App/Middleware/JsonpDetector as to the global middleware array.
  3. In app/Middleware/JsonpDetector.js, replace the file with the file from this gist.
'use strict'
const Config = use('Config')
/**
* JSON-P middleware for AdonisJS 4.1
* https://gist.github.com/Sleavely/da1ac50e1ea614b4171beae7868ec3ed
*/
class JsonpDetector {
async handle ({ request, response }, next) {
// Run routes
await next()
// Okay, so now there should be a request ready to be sent.
// Lets figure out if making it JSONP is relevant by making sure that:
// - The JSONP callback parameter is set
// - The user didnt use response.json() or response.jsonp()
// - The content doesnt look like XML/HTML
const queryParams = request.get()
if(typeof queryParams[ Config.get('app.http.jsonpCallback') ] === 'undefined')
{
// No JSONP callback set
return;
}
if(response.lazyBody.method != 'send')
{
// response.json() or response.jsonp() was used
return;
}
if(typeof response.lazyBody.content == 'string')
{
// XML-like?
if(response.lazyBody.content.trim().indexOf('<') === 0)
{
return;
}
}
response.jsonp(response.lazyBody.content)
}
}
module.exports = JsonpDetector
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment