Best JavaScript code snippet using karma
api.response.handlers.js
Source:api.response.handlers.js
...43 * Sends Success > OK to the client with a json response44 * @param {object} json45 */46 express.response.ok = function (json) {47 setNoCacheHeaders(this);48 this.header('Content-Type', 'application/json; charset=utf-8');49 this.status(200);50 this.json(json);51 };52 /**53 * Sends Success > OK to the client with a json response54 * @param {object} json55 */56 express.response.created = function (json) {57 setNoCacheHeaders(this);58 this.header('Content-Type', 'application/json; charset=utf-8');59 this.status(201);60 this.json(json);61 };62 /**63 * Sends Success > No Content to the client64 */65 express.response.noContent = function () {66 setNoCacheHeaders(this);67 this.status(204);68 this.send();69 };70 /**71 * Sends Client error > Bad Request with custom messages72 * @param {string} errorMessage73 */74 express.response.badRequest = function (errorMessage) {75 setNoCacheHeaders(this);76 this.header('Content-Type', 'application/json; charset=utf-8');77 this.status(400);78 this.json({79 errorCode: errorCodes.badRequest.unknown,80 errorMessage: errorMessage || 'Bad Request',81 });82 };83 /**84 * Sends Client error > Bad Request with predefined messages for resource that cannot be deleted.85 * @param {string} resourceName86 */87 express.response.cannotBeDeleted = function (resourceName) {88 setNoCacheHeaders(this);89 this.header('Content-Type', 'application/json; charset=utf-8');90 this.status(400);91 this.json({92 errorCode: errorCodes.badRequest.cannotBeDeleted,93 errorMessage: `${resourceName} cannot be deleted because it is used by another resource`,94 });95 };96 /**97 * Sends client error > bad request with predefined messages for invalid field98 * @param {string} fieldName99 */100 express.response.incorrectValue = function (fieldName) {101 setNoCacheHeaders(this);102 this.header('Content-Type', 'application/json; charset=utf-8');103 this.status(400);104 this.json({105 errorCode: errorCodes.badRequest.incorrectValue,106 errorMessage: `Incorrect value for ${fieldName}`,107 });108 };109 /**110 * Sends client error > Bad Request with predefined messages for date in the future111 * @param {string} fieldName112 */113 express.response.cannotBeInFuture = function (fieldName) {114 setNoCacheHeaders(this);115 this.header('Content-Type', 'application/json; charset=utf-8');116 this.status(400);117 this.json({118 errorCode: errorCodes.badRequest.cannotBeInFuture,119 errorMessage: `${fieldName} cannot be in the future`,120 });121 };122 /**123 * Sends client error > Unauthorized with predefined messages for wrong credentials124 */125 express.response.wrongCredentials = function () {126 setNoCacheHeaders(this);127 this.header('Content-Type', 'application/json; charset=utf-8');128 this.status(401);129 this.json({130 errorCode: errorCodes.unauthorised.wrongCredentials,131 errorMessage: 'Wrong credentials',132 });133 };134 /**135 * Sends client error > Unauthorized with predefined messages for invalid token136 */137 express.response.invalidToken = function () {138 setNoCacheHeaders(this);139 this.header('Content-Type', 'application/json; charset=utf-8');140 this.status(401);141 this.json({142 errorCode: errorCodes.unauthorised.invalidToken,143 errorMessage: 'Invalid token',144 });145 };146 /**147 * Sends client error > Unauthorized with predefined messages for missing token148 */149 express.response.missingToken = function () {150 setNoCacheHeaders(this);151 this.header('Content-Type', 'application/json; charset=utf-8');152 this.status(401);153 this.json({154 errorCode: errorCodes.unauthorised.missingToken,155 errorMessage: 'Missing token',156 });157 };158 /**159 * Sends client error > Forbidden with predefined messages160 */161 express.response.missingToken = function () {162 setNoCacheHeaders(this);163 this.header('Content-Type', 'application/json; charset=utf-8');164 this.status(403);165 this.json({166 errorCode: errorCodes.forbidden.forbidden,167 errorMessage: 'Forbidden',168 });169 };170 /**171 * Sends client error > Forbidden with predefined messages for not having clearance172 */173 express.response.noClearance = function () {174 setNoCacheHeaders(this);175 this.header('Content-Type', 'application/json; charset=utf-8');176 this.status(403);177 this.json({178 errorCode: errorCodes.forbidden.noClearance,179 errorMessage: 'You do not have clearance for this action',180 });181 };182 /**183 * Sends client error > Forbidden with predefined messages for not having write privileges184 */185 express.response.noWritePrivilege = function () {186 setNoCacheHeaders(this);187 this.header('Content-Type', 'application/json; charset=utf-8');188 this.status(403);189 this.json({190 errorCode: errorCodes.forbidden.noWritePrivilege,191 errorMessage: 'You do not have write privileges',192 });193 };194 /**195 * Sends client error > Forbidden with predefined messages for not having access to the requested store196 */197 express.response.cannotAccessStore = function () {198 setNoCacheHeaders(this);199 this.header('Content-Type', 'application/json; charset=utf-8');200 this.status(403);201 this.json({202 errorCode: errorCodes.forbidden.cannotAccessStore,203 errorMessage: 'You do not have access to the requested store',204 });205 };206 /**207 * Sends client error > not found with predefined messages208 * @param {string} resourceName209 */210 express.response.notFound = function (resourceName) {211 setNoCacheHeaders(this);212 this.header('Content-Type', 'application/json; charset=utf-8');213 this.status(404);214 this.json({215 errorCode: errorCodes.notFound,216 errorMessage: `${resourceName} not found`,217 });218 };219 /**220 * Sends server error > internal server error with custom messages221 * @param {string} errorMessage222 */223 express.response.internalServerError = function (errorMessage) {224 setNoCacheHeaders(this);225 this.header('Content-Type', 'application/json; charset=utf-8');226 this.status(500);227 this.json({228 errorCode: errorCodes.internalServerError,229 errorMessage: errorMessage || 'Internal Server Error'230 });231 };232 /**233 * Accepts an errorType constant and calls the appropriate function with errorContent234 * @param {object} error235 * @param {object} req236 * @property {string} error.errorType Type of error to send. Types can be found in error.types.js237 * @property {string} error.errorContent Varies for each errorType238 * @property {object} error.baseError first error thrown and caught239 */240 express.response.handleError = function (error, req = null) {241 setNoCacheHeaders(this);242 const {errorType, errorContent} = error;243 error.errorTime = new moment();244 if (req) {245 errors.req = {};246 if (req.headers) {247 error.req.origin = req.headers.origin || undefined;248 error.req.referer = req.headers.referer || undefined;249 error.req.userAgent = req.headers['user-agent'] || undefined;250 }251 error.req.url = req.url || undefined;252 error.req.originalUrl = req.originalUrl || undefined;253 error.req.body = req.body || undefined;254 }255 console.error(error);256 if (errorType && this[errorType] && typeof this[errorType] === 'function') {257 this[errorType](errorContent);258 } else {259 this.internalServerError(errorContent);260 }261 };262 /**263 * Sends Success > OK to the client with a plain/text response264 * @param {*} text265 */266 express.response.sendPlainText = function (text) {267 setNoCacheHeaders(this);268 this.header('Content-Type', 'text/plain; charset=utf-8');269 this.status(200);270 this.send(text);271 };272};...
server.mjs
Source:server.mjs
...62 ctx.throw(500, `Node ${name} not found`);63 }64 return node;65}66function setNoCacheHeaders(ctx) {67 ctx.set("Cache-Control", "no-store, no-cache, must-revalidate");68 ctx.set("Pragma", "no-cache");69 ctx.set("Expires", 0);70}71function tokenGenerator(authService) {72 return async (ctx, next) => {73 const q = ctx.request.body;74 try {75 const result = await authService.accessTokenGenerator(q.username, q.password);76 ctx.body = {77 access_token: result.access_token78 };79 return next();80 } catch (e) {81 console.log(e);82 ctx.throw(401, "Authentication failed");83 }84 };85}86export async function initializeServer(bus) {87 const config = bus.config;88 const sp = bus.sp;89 const app = new Koa();90 bus.app = app;91 const router = Router({92 notFound: async (ctx, next) => {93 console.log("route not found", ctx.request.url);94 return next();95 }96 });97 router.addRoute(98 "POST",99 "/authenticate",100 BodyParser(),101 tokenGenerator(sp.services.auth)102 );103 // middleware to restrict access to token holding requests104 const restricted = KoaJWT({105 secret: config.auth.jwt.public106 });107 router.addRoute("GET", "/authorize", async (ctx, next) => {108 body = {109 ...config.auth.oauth2110 };111 return next();112 });113 router.addRoute("GET", "/nodes/state", restricted, async (ctx, next) => {114 setNoCacheHeaders(ctx);115 ctx.body = await Promise.all(bus.nodes.map(node => node.state()));116 return next();117 });118 router.addRoute("GET", "/node/:node/state", restricted, async (ctx, next) => {119 setNoCacheHeaders(ctx);120 const node = getNode(bus.nodes, ctx.params.node, ctx);121 ctx.body = await node.state();122 return next();123 });124 router.addRoute(125 "POST",126 "/node/:node/restart",127 restricted,128 async (ctx, next) => {129 const node = getNode(bus.nodes, ctx.params.node, ctx);130 await node.restart();131 ctx.body = {};132 return next();133 }134 );135 router.addRoute("POST", "/node/:node/stop", restricted, async (ctx, next) => {136 const node = getNode(bus.nodes, ctx.params.node, ctx);137 node.stop();138 ctx.body = {};139 return next();140 });141 router.addRoute(142 "POST",143 "/node/:node/reload",144 restricted,145 async (ctx, next) => {146 const node = getNode(bus.nodes, ctx.params.node, ctx);147 node.reload();148 ctx.body = {};149 return next();150 }151 );152 router.addRoute("GET", "/groups", restricted, async (ctx, next) => {153 setNoCacheHeaders(ctx);154 const rg = [];155 for await (const group of sp.repositories.provider.repositoryGroups(156 ctx.query.pattern157 )) {158 rg.push(group.toJSON());159 }160 ctx.body = rg;161 return next();162 });163 router.addRoute("GET", "/repositories", restricted, async (ctx, next) => {164 setNoCacheHeaders(ctx);165 const rs = [];166 for await (const repository of sp.repositories.provider.repositories(167 ctx.query.pattern168 )) {169 rs.push(repository.toJSON());170 }171 ctx.body = rs;172 return next();173 });174 router.addRoute("GET", "/queues", restricted, async (ctx, next) => {175 setNoCacheHeaders(ctx);176 ctx.body = await Promise.all(177 Object.keys(bus.queues).map(async name => {178 const queue = bus.queues[name];179 return queueDetails(name, queue);180 })181 );182 return next();183 });184 router.addRoute("GET", "/queue/:queue", restricted, async (ctx, next) => {185 setNoCacheHeaders(ctx);186 ctx.body = await queueDetails(ctx.params.queue, getQueue(bus.queues, ctx));187 return next();188 });189 router.addRoute(190 "POST",191 "/queue/:queue/add",192 restricted,193 BodyParser(),194 async (ctx, next) => {195 const queue = getQueue(bus.queues, ctx);196 await queue.add(ctx.request.body);197 ctx.body = {};198 return next();199 }200 );201 router.addRoute(202 "POST",203 "/queue/:queue/pause",204 restricted,205 async (ctx, next) => {206 const queue = getQueue(bus.queues, ctx);207 await queue.pause();208 ctx.body = {};209 return next();210 }211 );212 router.addRoute(213 "POST",214 "/queue/:queue/resume",215 restricted,216 async (ctx, next) => {217 const queue = getQueue(bus.queues, ctx);218 await queue.resume();219 ctx.body = {};220 return next();221 }222 );223 router.addRoute(224 "POST",225 "/queue/:queue/empty",226 restricted,227 async (ctx, next) => {228 const queue = getQueue(bus.queues, ctx);229 await queue.clean(5000);230 await queue.empty();231 ctx.body = {};232 return next();233 }234 );235 router.addRoute(236 "GET",237 "/queue/:queue/jobs",238 restricted,239 async (ctx, next) => {240 setNoCacheHeaders(ctx);241 //ctx.query.states;242 const queue = getQueue(bus.queues, ctx);243 ctx.body = (244 await queue.getJobs(245 [246 "active",247 "waiting",248 "completed",249 "paused",250 "failed",251 "delayed"252 ] /*, { asc: true }*/253 )254 ).map(job => {255 return {256 id: Number(job.id),257 attemptsMade: job.attemptsMade,258 processedOn: job.processedOn,259 finishedOn: job.finishedOn,260 ...job.data261 };262 });263 return next();264 }265 );266 router.addRoute(267 "POST",268 "/queue/:queue/job/:job/cancel",269 restricted,270 async (ctx, next) => {271 const job = await getJob(bus.queues, ctx);272 await job.discard();273 ctx.body = {};274 //ctx.throw(500, `Unable to cancel job ${ctx.params.job}`);275 return next();276 }277 );278 router.addRoute(279 "POST",280 "/queue/:queue/job/:job/rerun",281 restricted,282 async (ctx, next) => {283 const job = await getJob(bus.queues, ctx);284 await job.retry();285 ctx.body = {};286 return next();287 }288 );289 router.addRoute(290 "GET",291 "/queue/:queue/job/:job",292 restricted,293 async (ctx, next) => {294 setNoCacheHeaders(ctx);295 const job = await getJob(bus.queues, ctx);296 ctx.body = {297 id: job.id,298 state: await job.getState(),299 attemptsMade: job.attemptsMade,300 processedOn: job.processedOn,301 finishedOn: job.processedOn,302 ...job.data303 };304 return next();305 }306 );307 router.addRoute(308 "GET",...
index.js
Source:index.js
...11 var transporter = options.storage.type === 'local' ? require('./lib/transport/local.js') : require('./lib/transport/aws.js');12 transporter = transporter(options);13 var fileUploader = {};14 fileUploader.config = options;15 function setNoCacheHeaders(res) {16 res.setHeader('Pragma', 'no-cache');17 res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');18 res.setHeader('Content-Disposition', 'inline; filename="files.json"');19 }20 fileUploader.get = function(req, res, callback) {21 this.config.host = req.headers.host;22 setNoCacheHeaders(res);23 transporter.get(callback);24 };25 fileUploader.post = function(req, res, callback) {26 setNoCacheHeaders(res);27 var form = new formidable.IncomingForm();28 var tmpFiles = [];29 var files = [];30 var map = {};31 var fields = {};32 var redirect;33 this.config.host = req.headers.host;34 var configs = this.config;35 req.body = req.body || {};36 function finish(error, fileInfo) {37 if (error) return callback(error, {38 files: files39 }, redirect);40 if (!fileInfo) return callback(null, {...
_request_handler.js
Source:_request_handler.js
...54 break;55 case 'HEAD':56 case 'GET':57 if (req.url === '/') {58 setNoCacheHeaders();59 if (req.method === 'GET') {60 handler.get();61 } else {62 res.end();63 }64 } else {65 fileServer.serve(req, res);66 }67 break;68 case 'POST':69 setNoCacheHeaders();70 handler.post();71 break;72 case 'DELETE':73 handler.destroy();74 break;75 default:76 res.statusCode = 405;77 res.end();78 }79 fileServer.respond = function (pathname, status, _headers, files, stat, req, res, finish) {80 _headers['X-Content-Type-Options'] = 'nosniff';81 if (!options.imageTypes.test(files[0])) {82 _headers['Content-Type'] = 'application/octet-stream';83 _headers['Content-Disposition'] = 'attachment; filename="' +...
common.js
Source:common.js
1/**2 * This module contains some common helpers shared between middlewares3 */4var mime = require('mime')5var log = require('../logger').create('web-server')6var PromiseContainer = function () {7 var promise8 this.then = function (success, error) {9 return promise.then(success, error)10 }11 this.set = function (newPromise) {12 promise = newPromise13 }14}15var serve404 = function (response, path) {16 log.warn('404: ' + path)17 response.writeHead(404)18 return response.end('NOT FOUND')19}20var createServeFile = function (fs, directory) {21 var cache = Object.create(null)22 return function (filepath, response, transform, content) {23 var responseData24 if (directory) {25 filepath = directory + filepath26 }27 if (!content && cache[filepath]) {28 content = cache[filepath]29 }30 // serve from cache31 if (content) {32 response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain'))33 // call custom transform fn to transform the data34 responseData = transform && transform(content) || content35 response.writeHead(200)36 log.debug('serving (cached): ' + filepath)37 return response.end(responseData)38 }39 return fs.readFile(filepath, function (error, data) {40 if (error) {41 return serve404(response, filepath)42 }43 cache[filepath] = data.toString()44 response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain'))45 // call custom transform fn to transform the data46 responseData = transform && transform(data.toString()) || data47 response.writeHead(200)48 log.debug('serving: ' + filepath)49 return response.end(responseData)50 })51 }52}53var setNoCacheHeaders = function (response) {54 response.setHeader('Cache-Control', 'no-cache')55 response.setHeader('Pragma', 'no-cache')56 response.setHeader('Expires', (new Date(0)).toString())57}58var setHeavyCacheHeaders = function (response) {59 response.setHeader('Cache-Control', ['public', 'max-age=31536000'])60}61// PUBLIC API62exports.PromiseContainer = PromiseContainer63exports.createServeFile = createServeFile64exports.setNoCacheHeaders = setNoCacheHeaders65exports.setHeavyCacheHeaders = setHeavyCacheHeaders...
uploader.js
Source:uploader.js
...43 if(!conf){44 return;45 }46 var handler = setupHandler(req, res);47 setNoCacheHeaders(req, res);48 handler.post(conf);49};50exports.opts = function(req, res){51 if(!checkHost(req, res)){52 return;53 }54 res.send(200);55};56exports.simpleUpload = function(req, res){57 var conf = checkHost(req, res, true);58 if(!conf){59 return;60 }61 var handler = setupHandler(req, res);62 setNoCacheHeaders(req, res);63 handler.post(conf);64};65exports.simpleOpts = function(req, res){66 if(!checkHost(req, res, true)){67 return;68 }69 res.send(200);...
Using AI Code Generation
1var setNoCacheHeaders = function (res) {2};3var setNoCacheHeaders = function (res) {4};5var setNoCacheHeaders = function (res) {6};7var setNoCacheHeaders = function (res) {8};9var setNoCacheHeaders = function (res) {10};11var setNoCacheHeaders = function (res) {12};
Using AI Code Generation
1var KarmaServer = require('karma').Server;2var server = new KarmaServer({3}, function(exitCode) {4 console.log('Karma has exited with ' + exitCode);5 process.exit(exitCode);6});7server.setNoCacheHeaders();8server.start();
Using AI Code Generation
1var setNoCacheHeaders = function (headers) {2 headers['Cache-Control'] = 'no-cache, no-store, must-revalidate';3 headers.Pragma = 'no-cache';4 headers.Expires = '0';5 return headers;6};7module.exports = function (config) {8 config.set({
Using AI Code Generation
1module.exports = function(config) {2 config.set({3 preprocessors: {4 },5 coverageReporter: {6 },7 });8};9var app = (function() {10 return {11 add: function(a, b) {12 return a + b;13 }14 };15})();16describe('app', function() {17 it('should add two numbers', function() {18 expect(app.add(2, 3)).toBe(5);19 });20});21module.exports = function(config) {22 config.set({23 preprocessors: {24 },25 coverageReporter: {26 },27 });28};29var app = (function() {30 return {31 add: function(a
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!