UNPKG

ac-node

Version:

A common module for building Atlassian Connect add-ons

82 lines (71 loc) 2.07 kB
var urls = require('url'); module.exports = function () { var routes = { GET: [], POST: [], PUT: [], DELETE: [] }; var notFoundHandler; function mock(url, options, callback) { var args = normalize(url, options, callback); url = args[0]; options = args[1]; callback = args[2]; var parsed = urls.parse(url); var route = parsed.protocol + '//' + parsed.host + parsed.pathname; var ctx = {route: route}; var handler; routes[options.method].some(function (entry) { if (entry.matcher.test(route)) { handler = entry.handler; } return !!handler; }); if (handler) { handler.call(ctx, url, options, callback); } else if (notFoundHandler) { notFoundHandler.call(ctx, url, options, callback); } else { callback(new Error('No handler found for mock request route ' + route)); } } function normalize(url, options, callback) { if (typeof url === 'object') { callback = options; options = url; url = options.url || options.uri; } return [url, options, callback]; } mock.get = function (url, options, callback) { var args = normalize(url, options, callback); args[1].method = 'GET'; return mock.apply(null, args); }; mock.post = function (url, options, callback) { var args = normalize(url, options, callback); args[1].method = 'POST'; return mock.apply(null, args); }; mock.put = function (url, options, callback) { var args = normalize(url, options, callback); args[1].method = 'PUT'; return mock.apply(null, args); }; mock.del = function (url, options, callback) { var args = normalize(url, options, callback); args[1].method = 'DELETE'; return mock.apply(null, args); }; mock.mount = function (method, route, handler) { routes[method].push({ matcher: new RegExp('^' + route.replace(/\*/g, '[^/]+') + '$'), handler: handler }); }; mock.notFound = function (handler) { notFoundHandler = handler; }; return mock; };