Best JavaScript code snippet using playwright-internal
SecurityController.js
Source:SecurityController.js
1const bodyParser = require("body-parser");2const cookieParser = require("cookie-parser");3const cors = require("cors");4const jwt = require("jsonwebtoken");5const csrf = require("csurf");6const { buildCheckFunction } = require("express-validator/check");7const check = buildCheckFunction(["params", "body", "query"]);8const BassController = require("../../library/BaseController");9const {10 models: {11 user: { emailConfirmation }12 }13} = require("../../config");14const User = require("../../models/User");15const Token = require("../../models/Token");16const passport = require("../../library/helpers/passport");17const {18 validationErrors,19 bindMethods,20 wrapAsync,21 getParam,22 getField23} = require("../../library/helpers/utils");24/**25 * Security controller handles login, confirm email and recover password.26 */27module.exports = class SecurityController extends BassController {28 /**29 * Configuration.30 */31 constructor() {32 super();33 // Paths:34 this.paths.login = "/security/login";35 this.paths.confirm = "/security/confirm/:id/:code";36 this.paths.resend = "/security/resend";37 this.paths.recover = "/security/recover";38 this.paths.password = "/security/password/:id/:code";39 // Validations:40 this.validators.login = [41 check("login", "Invalid Login, should be alpha-numeric.")42 .exists({43 checkNull: true,44 checkFalsy: true45 })46 .isAlphanumeric()47 .isLength({ min: 3 }),48 check("password", "Invalid Password, should be alpha-numeric.")49 .exists({50 checkNull: true,51 checkFalsy: true52 })53 .isAlphanumeric()54 .isLength({ min: 4 }),55 check("redirectUrl", "Param 'redirectUrl' should be a url.")56 .optional()57 .isURL({ require_tld: false, require_protocol: true })58 ];59 this.validators.confirm = [60 check("id", "Param 'id' should be an integer.")61 .exists({62 checkNull: true,63 checkFalsy: true64 })65 .isInt(),66 check("code", "Param 'code' should be a string and 32 characters long.")67 .exists({68 checkNull: true,69 checkFalsy: true70 })71 .isString()72 .isLength({ min: 32, max: 32 })73 ];74 this.validators.resend = [75 check("email", "Invalid email address.")76 .exists({77 checkNull: true,78 checkFalsy: true79 })80 .isEmail()81 .isLength({ min: 3 })82 ];83 this.validators.recover = [84 check("email", "Invalid email address.")85 .exists({86 checkNull: true,87 checkFalsy: true88 })89 .isEmail()90 .isLength({ min: 3 })91 ];92 this.validators.password = [93 check("password", "Invalid Password, should be alpha-numeric.")94 .exists({95 checkNull: true,96 checkFalsy: true97 })98 .isAlphanumeric()99 .isLength({ min: 4 }),100 check(101 "confirm_password",102 "Invalid confirm password, should be alpha-numeric."103 )104 .exists({105 checkNull: true,106 checkFalsy: true107 })108 .isAlphanumeric()109 .isLength({ min: 4 }),110 check("id", "Param 'id' should be an integer.")111 .exists({112 checkNull: true,113 checkFalsy: true114 })115 .isInt(),116 check("code", "Param 'code' should be a string and 32 characters long.")117 .exists({118 checkNull: true,119 checkFalsy: true120 })121 .isString()122 .isLength({ min: 32, max: 32 })123 ];124 // CORS:125 this.cors = {126 methods: ["GET", "POST"],127 allowedHeaders: ["Content-Type"],128 exposedHeaders: ["Authorization"]129 };130 // CSRF:131 this.csrf = [csrf({ cookie: true })];132 // To get 'this' in instance methods:133 bindMethods(this, [134 "actionLoginGet",135 "actionLoginPost",136 "actionConfirmGet",137 "actionResendGet",138 "actionResendPost",139 "actionRecoverGet",140 "actionRecoverPost",141 "actionPasswordGet",142 "actionPasswordPost"143 ]);144 }145 /**146 * Returns express.Router() configured with paths/middleware.147 */148 initRouter() {149 this.router.use(cookieParser());150 this.router.use(this.paths.login, cors(this.cors));151 this.router.use(152 this.paths.login,153 // Content-Type: application/json154 bodyParser.json()155 );156 this.router.get(this.paths.login, wrapAsync(this.actionLoginGet));157 this.router.post(158 this.paths.login,159 this.validators.login,160 wrapAsync(this.actionLoginPost)161 );162 this.router.get(163 this.paths.confirm,164 this.validators.confirm,165 wrapAsync(this.actionConfirmGet)166 );167 this.router.get(168 this.paths.resend,169 this.csrf,170 wrapAsync(this.actionResendGet)171 );172 this.router.post(173 this.paths.resend,174 this.validators.resend.concat(this.csrf),175 wrapAsync(this.actionResendPost)176 );177 this.router.get(178 this.paths.recover,179 this.csrf,180 wrapAsync(this.actionRecoverGet)181 );182 this.router.post(183 this.paths.recover,184 this.validators.recover.concat(this.csrf),185 wrapAsync(this.actionRecoverPost)186 );187 this.router.get(188 this.paths.password,189 this.csrf,190 wrapAsync(this.actionPasswordGet)191 );192 this.router.post(193 this.paths.password,194 this.validators.password.concat(this.csrf),195 wrapAsync(this.actionPasswordPost)196 );197 return this.router;198 }199 /**200 * Utils: construct params passed to:201 * views/security/login.ejs202 */203 loginViewParams(req, errors) {204 return {205 errors: errors,206 fields: ["login", "password", "redirectUrl"],207 login: getField(req, "login"),208 password: getField(req, "password")209 };210 }211 /**212 * GET security/login213 */214 async actionLoginGet(req, res) {215 res.render("security/login", this.loginViewParams(req, []));216 }217 /**218 * POST security/login219 */220 async actionLoginPost(req, res) {221 // Content type222 let isJsonContentType = false;223 if (req.headers["content-type"] === "application/json") {224 isJsonContentType = true;225 }226 // Check validation errors227 const errors = validationErrors(req);228 if (!errors.isEmpty()) {229 // mapped() means field name as object property. Specify fields[] in partials/errors.ejs230 if (isJsonContentType) {231 // 400 Bad Request232 return res.status(400).send({233 errors: errors.mapped()234 });235 } else {236 return res.render(237 "security/login",238 this.loginViewParams(req, errors.mapped())239 );240 }241 }242 // Try loading user243 const login = getField(req, "login");244 const user = await User.query()245 .where({ username: login })246 .orWhere({ email: login })247 .first();248 // User not found249 if (!user) {250 if (isJsonContentType) {251 // 404 Not Found252 return res.status(404).send({253 errors: { login: { message: "Incorrect login." } }254 });255 } else {256 return res.render(257 "security/login",258 this.loginViewParams(req, {259 login: { message: "Incorrect login." }260 })261 );262 }263 }264 // Incorrect password265 const password = getField(req, "password");266 const validPassword = await user.verifyPassword(password);267 if (!validPassword) {268 if (isJsonContentType) {269 // 404 Not Found270 return res.status(404).send({271 errors: { password: { message: "Incorrect password." } }272 });273 } else {274 return res.render(275 "security/login",276 this.loginViewParams(req, {277 password: { message: "Incorrect password." }278 })279 );280 }281 }282 // Requires confirmation283 if (emailConfirmation && !user.confirmed_at) {284 if (isJsonContentType) {285 // 400 Bad Request286 return res.status(400).send({287 errors: { login: { message: "Email confirmation required." } }288 });289 } else {290 return res.render(291 "security/login",292 this.loginViewParams(req, {293 login: { message: "Email confirmation required." }294 })295 );296 }297 }298 // Generate token299 const payload = { id: user.id };300 jwt.sign(301 payload,302 passport.jwt.secretOrKey,303 {304 expiresIn: passport.jwt.expiresIn305 },306 // Callback307 (err, token) => {308 if (err) throw err;309 // Send Authorization header310 res.header("Authorization", token);311 // Send Set-Cookie header312 res.cookie("Authorization", token, {313 httpOnly: false314 });315 if (isJsonContentType) {316 // 200 OK317 return res.status(200).send({318 Authorization: token319 });320 }321 // Redirect322 const redirectUrl = getParam(req, "redirectUrl", "/");323 return res.redirect(redirectUrl);324 }325 );326 }327 /**328 * Load token (used by confirm/password actions)329 */330 async loadToken(req, type) {331 const id = getParam(req, "id");332 const code = getParam(req, "code");333 const token = await Token.query()334 .where({335 user_id: id,336 type: type,337 code: code338 })339 .first();340 return token;341 }342 /**343 * Parse token (used by confirm/password actions)344 *345 * @param {Token} token346 */347 async parseToken(token) {348 /**349 * @property {User} user350 */351 const user = await token.$relatedQuery("user");352 const username = user.username;353 const notExpired = !token.expired();354 return {355 user,356 username,357 notExpired358 };359 }360 /**361 * Delete token (used by confirm/password actions)362 *363 * @param {Token} token364 */365 async deleteToken(token) {366 await Token.query().deleteById([token.type, token.user_id, token.code]);367 }368 /**369 * Utils: construct params passed to:370 * views/security/error.ejs371 * views/security/success.ejs372 */373 confirmViewParams(title, message, errors = {}) {374 return {375 title: title,376 message: message,377 errors: errors,378 fields: ["id", "code"]379 };380 }381 /**382 * GET security/confirm/:id/:code383 */384 async actionConfirmGet(req, res) {385 // Check validation errors386 const errors = validationErrors(req);387 if (!errors.isEmpty()) {388 return res.render(389 "security/error",390 this.confirmViewParams("404", "Bad Request", errors.mapped())391 );392 }393 // Load token394 const token = await this.loadToken(req, Token.TYPE_CONFIRMATION);395 // Not found396 if (!token) {397 return res.render(398 "security/error",399 this.confirmViewParams("Confirmation Failed", "Token Not Found")400 );401 }402 // Parse token403 const { user, username, notExpired } = await this.parseToken(token);404 // Token not expired405 let view = "security/success";406 let title = "Email Confirmed";407 let message = "Thank you " + username + ", your email has been confirmed";408 if (notExpired) {409 // Confirmed at timestamp410 await user.$query().patch({411 confirmed_at: new Date().toISOString()412 });413 }414 // Token expired415 else {416 view = "security/error";417 title = "Confirmation Failed";418 message = " Token has expired";419 }420 await this.deleteToken(token);421 // Render422 res.render(view, this.confirmViewParams(title, message));423 }424 /**425 * Utils: construct params passed to:426 * views/security/password.ejs427 * views/security/error.ejs428 * views/security/success.ejs429 */430 passwordViewParams(req, title, message, errors = {}) {431 return {432 csrf: req.csrfToken(),433 errors: errors,434 fields: ["password", "confirm_password"],435 title: title,436 message: message,437 password: getField(req, "password"),438 confirm_password: getField(req, "confirm_password")439 };440 }441 /**442 * GET security/password/:id/:code443 */444 async actionPasswordGet(req, res) {445 res.render("security/password", this.passwordViewParams(req, {}));446 }447 /**448 * POST security/password/:id/:code449 */450 async actionPasswordPost(req, res) {451 // Check validation errors452 const errors = validationErrors(req);453 if (!errors.isEmpty()) {454 return res.render(455 "security/password",456 this.passwordViewParams(req, "404", "Bad Request", errors.mapped())457 );458 }459 // Check confirm password matches password460 const password = getField(req, "password");461 const confirm_password = getField(req, "confirm_password");462 if (confirm_password !== password) {463 return res.render(464 "security/password",465 this.passwordViewParams(req, "404", "Bad Request", {466 confirm_password: {467 message: "Confirm password doesn't match password."468 }469 })470 );471 }472 // Load token473 const token = await this.loadToken(req, Token.TYPE_RECOVERY);474 // Not found475 if (!token) {476 return res.render(477 "security/error",478 this.passwordViewParams(479 req,480 "Change password Failed",481 "Token Not Found"482 )483 );484 }485 // Parse token486 const { username, user, notExpired } = await this.parseToken(token);487 // Token not expired488 let view = "security/success";489 let title = "Password Changed";490 let message = "Thank you " + username + ", your password has been changed";491 if (notExpired) {492 // Change password493 await user.$query().patch({494 password: getField(req, "password")495 });496 }497 // Token expired498 else {499 view = "security/error";500 title = "Change Password Failed";501 message = " Token has expired";502 }503 await this.deleteToken(token);504 // Render505 res.render(view, this.passwordViewParams(req, title, message));506 }507 /**508 * Utils: construct params passed to:509 * views/security/resend.ejs510 * views/security/success.ejs511 */512 resendViewParams(req, errors = {}) {513 return {514 csrf: req.csrfToken(),515 errors: errors,516 fields: ["email"],517 email: getField(req, "email")518 };519 }520 /**521 * GET security/resend522 */523 async actionResendGet(req, res) {524 res.render("security/resend", this.resendViewParams(req, {}));525 }526 /**527 * POST security/resend528 */529 async actionResendPost(req, res) {530 // Check validation errors531 const errors = validationErrors(req);532 if (!errors.isEmpty()) {533 return res.render(534 "security/resend",535 this.resendViewParams(req, errors.mapped())536 );537 }538 // Try loading user539 const email = getField(req, "email");540 const user = await User.query()541 .where({ email: email })542 .first();543 // User not found544 if (!user) {545 return res.render(546 "security/resend",547 this.resendViewParams(req, {548 email: { message: "Email not found." }549 })550 );551 }552 // Send confirmation553 await user.sendConfirmationEmail();554 // Render555 res.render("security/success", {556 title: "Email Sent",557 message: "A confirmation email has been sent to " + email558 });559 }560 /**561 * Utils: construct params passed to:562 * views/security/recover.ejs563 * views/security/success.ejs564 */565 recoverViewParams(req, errors = {}) {566 return {567 csrf: req.csrfToken(),568 errors: errors,569 fields: ["email"],570 email: getField(req, "email")571 };572 }573 /**574 * GET security/recover575 */576 async actionRecoverGet(req, res) {577 res.render("security/recover", this.recoverViewParams(req, {}));578 }579 /**580 * POST security/recover581 */582 async actionRecoverPost(req, res) {583 // Check validation errors584 const errors = validationErrors(req);585 if (!errors.isEmpty()) {586 return res.render(587 "security/recover",588 this.recoverViewParams(req, errors.mapped())589 );590 }591 // Try loading user592 const email = getField(req, "email");593 const user = await User.query()594 .where({ email: email })595 .first();596 // User not found597 if (!user) {598 return res.render(599 "security/recover",600 this.resendViewParams(req, {601 email: { message: "Email not found." }602 })603 );604 }605 // Send recovery606 await user.sendRecoveryEmail();607 // Render608 res.render("security/success", {609 title: "Email Sent",610 message: "A recovery email has been sent to " + email611 });612 }...
core.js
Source:core.js
1(function () {2 //Definisco un oggetto di base (LayerSupertype) che possiede al function per lereditarietà per l'ereditarietà 3 function AObject() { }4 AObject.extend = function (obj) {5 return AObject.__doExtend(AObject, obj);6 };7 AObject.newInstance = function () {8 return new AObject();9 };10 AObject.__doExtend = function (superType, obj) {11 var inerithed = function (c) {12 if (c === "__AObject_prototype") {13 } else {14 if (!$.isFunction(obj.ctor)) {15 obj.ctor = function () { superType.prototype.ctor.apply(this, arguments); };16 }17 obj.ctor.apply(this, arguments);18 }19 };20 inerithed.prototype = $.extend(new superType("__AObject_prototype"), obj);21 inerithed.super = superType.prototype;22 inerithed.newInstance = function () { return new inerithed(); };23 inerithed.extend = function (o) {24 return AObject.__doExtend(inerithed, o);25 };26 return inerithed;27 };28 AObject.prototype = {29 ctor: function () {30 }31 };32 var DBFactory = function () {33 this.basePath = Fenealweb.config.services.remoteApiBasePath;34 };35 DBFactory.prototype.createLoginService = function (data) {36 var route = Fenealweb.config.services.remoteLoginPath;37 return this.__doCreateService(false, route,data,null,'POST');38 };39 DBFactory.prototype.createService = function (params) { //isJsonContentType, route, data, token, method40 var defaults = {41 isJsonContentType: false,42 route: '',43 data: null,44 token: null,45 method: 'GET'46 };47 var data = $.extend(defaults, params);48 defaults.route = this.basePath + defaults.route;49 return this.__doCreateService(data.isJsonContentType, data.route, data.data, data.token, data.method);50 };51 DBFactory.prototype.__doCreateService = function (isJsonContentType, route, data, token, method) {52 53 //definisco il servizio54 var service = new AjaxService(token);55 //se sono dati json ne imposto il content type56 if (isJsonContentType)57 service.contentType= "application/json";58 else59 service.contentType = "application/x-www-form-urlencoded; charset=UTF-8";60 //se ci sono dati li trasformoi in stringa json61 //e li accodo al servizio62 if (isJsonContentType) {63 if (data) {64 if (typeof (data) == 'string') {65 service.data = data;66 }67 else {68 var stringified1 = JSON.stringify(data);69 service.data = stringified1;70 }71 }72 } else {73 if (data)74 service.data = data;75 }76 77 78 service.url = route;79 if (method)80 service.method = method;81 return service;82 };83 84 //il servixio che devo creare deve avere la possibilità di :85 // -- inserire un eventuale token per le chiamate protette86 // -- deve avere una gestione centralizzata dell'errore legato al fatto di non essere loggato87 var AjaxService = AObject.extend({88 ctor: function (token) {89 AjaxService.super.ctor.call(this);90 //il token utilizzato per le chiamate protette91 this.token = token;92 this.data = {};93 //l'url a cui inviare i dati94 this.url = null;95 //il metodo utilizxzato di default96 this.method = "GET";97 //il tipo di dato che mi aspetto di ritorno98 this.dataType = "json";99 //il contentType utilizzato che puo anche essere application/x-www-form-urlencoded100 this.contentType = "application/json";101 },102 load : function () {103 var self = this;104 var d = $.Deferred();105 $.ajax({106 type: this.method,107 traditional: true,108 url: this.url,109 data: this.data,110 contentType: this.contentType,111 dataType: this.dataType,112 success: function (response) {113 114 //se non c'è una risposta dal server risolvo direttamente l'oggetto deferred115 if (!response) {116 d.resolve(response);117 return;118 }119 120 if (response.error === true) {121 d.reject(response.message);122 return;123 }124 //poiche tutte le chiamate restituiscono una silpme response125 //...126 d.resolve(response.value);127 },128 error: function (xhr, textStatus, errorThrown) {129 var error = textStatus;130 if (errorThrown)131 error = error + " - " + errorThrown;132 var merror = "Errore nella comunicazione con il server (" + error +")";133 134 d.reject(merror);135 },136 beforeSend: function (xhr) {137 138 if (self.token) {139 // xhr.setRequestHeader('Access-Control-Allow-Origin', '*');140 xhr.setRequestHeader('TOKEN', self.token);141 142 }143 }144 });145 return d.promise();146 }147 });148 149 Fenealweb.core = {};150 Fenealweb.core.AjaxService = AjaxService;151 Fenealweb.core.DBFactory = DBFactory;152 Fenealweb.core.AObject = AObject;...
validator.js
Source:validator.js
...14 });15 });16 });17}18function isJsonContentType(headers) {19 return headers.some(function (header) {20 return header.name === 'Content-Type' && header.value === 'application/json';21 });22}23function isValidRequestOrResponse(requestOrResponse) {24 if (isJsonContentType(requestOrResponse.headers)) {25 try {26 var body = requestOrResponse.body;27 jsonParser.parse(body);28 } catch (e) {29 return e;30 }31 }32 return true;33}34function errorPosition(example, action, resource, resourceGroup) {35 var output = [];36 if (resourceGroup.name) {37 output.push('group "' + resourceGroup.name + '"');38 }...
php-curl.js
Source:php-curl.js
1import { isJSONContentType } from "~/helpers/utils/contenttypes"2export const PhpCurlCodegen = {3 id: "php-curl",4 name: "PHP cURL",5 generator: ({6 url,7 pathName,8 queryString,9 auth,10 httpUser,11 httpPassword,12 bearerToken,13 method,14 rawInput,15 rawParams,16 rawRequestBody,17 contentType,18 headers,19 }) => {20 const requestString = []21 let genHeaders = []22 requestString.push(`<?php\n`)23 requestString.push(`$curl = curl_init();\n`)24 requestString.push(`curl_setopt_array($curl, array(\n`)25 requestString.push(` CURLOPT_URL => "${url}${pathName}${queryString}",\n`)26 requestString.push(` CURLOPT_RETURNTRANSFER => true,\n`)27 requestString.push(` CURLOPT_ENCODING => "",\n`)28 requestString.push(` CURLOPT_MAXREDIRS => 10,\n`)29 requestString.push(` CURLOPT_TIMEOUT => 0,\n`)30 requestString.push(` CURLOPT_FOLLOWLOCATION => true,\n`)31 requestString.push(` CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n`)32 requestString.push(` CURLOPT_CUSTOMREQUEST => "${method}",\n`)33 if (auth === "Basic Auth") {34 const basic = `${httpUser}:${httpPassword}`35 genHeaders.push(36 ` "Authorization: Basic ${window.btoa(unescape(encodeURIComponent(basic)))}",\n`37 )38 } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {39 genHeaders.push(` "Authorization: Bearer ${bearerToken}",\n`)40 }41 if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {42 let requestBody = rawInput ? rawParams : rawRequestBody43 if (44 !isJSONContentType(contentType) &&45 rawInput &&46 !contentType.includes("x-www-form-urlencoded")47 ) {48 const toRemove = /[\n {}]/gim49 const toReplace = /:/gim50 const parts = requestBody.replace(toRemove, "").replace(toReplace, "=>")51 requestBody = `array(${parts})`52 } else if (isJSONContentType(contentType)) {53 requestBody = JSON.stringify(requestBody)54 } else if (contentType.includes("x-www-form-urlencoded")) {55 if (requestBody.includes("=")) {56 requestBody = `"${requestBody}"`57 } else {58 const requestObject = JSON.parse(requestBody)59 requestBody = `"${Object.keys(requestObject)60 .map((key) => `${key}=${requestObject[key].toString()}`)61 .join("&")}"`62 }63 }64 if (contentType) {65 genHeaders.push(` "Content-Type: ${contentType}; charset=utf-8",\n`)66 }67 requestString.push(` CURLOPT_POSTFIELDS => ${requestBody},\n`)68 }69 if (headers.length > 0) {70 headers.forEach(({ key, value }) => {71 if (key) genHeaders.push(` "${key}: ${value}",\n`)72 })73 }74 if (genHeaders.length > 0 || headers.length > 0) {75 requestString.push(76 ` CURLOPT_HTTPHEADER => array(\n${genHeaders.join("").slice(0, -2)}\n )\n`77 )78 }79 requestString.push(`));\n`)80 requestString.push(`$response = curl_exec($curl);\n`)81 requestString.push(`curl_close($curl);\n`)82 requestString.push(`echo $response;\n`)83 return requestString.join("")84 },...
server.js
Source:server.js
1var fs = require('fs');2var express = require('express');3var _ = require('underscore');4var app = express();5app.use(express.bodyParser());6app.use(express.static('public'));7var FILENAME = "./db_data.json";8var todos = [];9function load(success) {10 fs.exists(FILENAME, function (exists) {11 if(!exists) { return success(); }12 fs.readFile(FILENAME, function (err, data) {13 if (err) throw err;14 try {15 todos = JSON.parse(data);16 success();17 } catch(e) {18 console.log("Could not read the file, it might be corrupted", e);19 console.log("Creating a new empty file");20 save(function() {21 console.log("Successfully created a new clean file");22 success();23 });24 }25 });26 });27}28function save(success) {29 var data = todos;30 fs.writeFile(FILENAME, JSON.stringify(data), function(err) {31 if(err) { throw err; }32 console.log("Saved latest changes to file");33 success();34 }); 35}36function isJSONContentType(req) {37 return req.headers['content-type'].indexOf("application/json") !== -1;38}39// Create40app.post('/api/todos', function(req, res) {41 console.log("POST /api/todos");42 43 if(!isJSONContentType(req)) {44 return res.send(400, "request content type was " + contentType + ", should be application/json");45 }46 var body = req.body;47 var id = Date.now();48 var newItem = {49 title : body.title,50 done : body.done || false,51 id: id52 }53 todos.push(newItem);54 save(function() {55 console.log("Created new item", newItem);56 return res.send(201, newItem);57 });58});59// Read60app.get('/api/todos', function(req, res){61 console.log("GET /api/todos");62 console.log("Returning all items");63 return res.send(todos);64});65// Update66app.put('/api/todos/:id', function(req, res){67 console.log("PUT /api/todos/:id");68 if(!isJSONContentType(req)) {69 return res.send(400, "request content type was " + contentType + ", should be application/json");70 }71 var itemToUpdate = _.find(todos, function(todo) {72 console.log(todo.id);73 return todo.id === Number(req.params.id);74 });75 if(!itemToUpdate) {76 return res.send(404);77 }78 itemToUpdate.title = _.isString(req.body.title) ? req.body.title : itemToUpdate.title;79 itemToUpdate.done = _.isBoolean(req.body.done) ? req.body.done : itemToUpdate.done;80 save(function() {81 console.log("Updated item", itemToUpdate);82 return res.send(204);83 });84});85// Delete86app.del('/api/todos/:id', function(req, res){87 console.log("DELETE /api/todos/:id");88 var itemToDelete = _.find(todos, function(item) {89 return item.id === Number(req.params.id);90 });91 todos = _.without(todos, itemToDelete);92 save(function() {93 console.log("Deleted item", itemToDelete);94 return res.send(204);95 });96});97load(function() {98 console.log("Loaded", todos.length, "items from file");99 console.log(todos);100 app.listen(3000);101 console.log('\nListening on port 3000\n');102 console.log('http://localhost:3000 to access the public HTML files');103 console.log('http://localhost:3000/api/todos to access Rest API\n');...
contenttypes.spec.js
Source:contenttypes.spec.js
1import { isJSONContentType } from "../contenttypes"2describe("isJSONContentType", () => {3 test("returns true for JSON content types", () => {4 expect(isJSONContentType("application/json")).toBe(true)5 expect(isJSONContentType("application/vnd.api+json")).toBe(true)6 expect(isJSONContentType("application/hal+json")).toBe(true)7 expect(isJSONContentType("application/ld+json")).toBe(true)8 })9 test("returns true for JSON types with charset specified", () => {10 expect(isJSONContentType("application/json; charset=utf-8")).toBe(true)11 expect(isJSONContentType("application/vnd.api+json; charset=utf-8")).toBe(12 true13 )14 expect(isJSONContentType("application/hal+json; charset=utf-8")).toBe(true)15 expect(isJSONContentType("application/ld+json; charset=utf-8")).toBe(true)16 })17 test("returns false for non-JSON content types", () => {18 expect(isJSONContentType("application/xml")).toBe(false)19 expect(isJSONContentType("text/html")).toBe(false)20 expect(isJSONContentType("application/x-www-form-urlencoded")).toBe(false)21 expect(isJSONContentType("foo/jsoninword")).toBe(false)22 })23 test("returns false for non-JSON content types with charset", () => {24 expect(isJSONContentType("application/xml; charset=utf-8")).toBe(false)25 expect(isJSONContentType("text/html; charset=utf-8")).toBe(false)26 expect(27 isJSONContentType("application/x-www-form-urlencoded; charset=utf-8")28 ).toBe(false)29 expect(isJSONContentType("foo/jsoninword; charset=utf-8")).toBe(false)30 })31 test("returns false for null/undefined", () => {32 expect(isJSONContentType(null)).toBe(false)33 expect(isJSONContentType(undefined)).toBe(false)34 })...
isJsonContentType.test.js
Source:isJsonContentType.test.js
...4 describe('returns true', () => {5 const jsonTypes = ['application/json', 'application/schema+json'];6 jsonTypes.forEach((contentType) => {7 it(`when given ${contentType}`, () => {8 assert.isTrue(isJsonContentType(contentType));9 });10 });11 });12 describe('returns false', () => {13 const nonJsonTypes = ['application/xml', 'text/plain'];14 nonJsonTypes.forEach((contentType) => {15 it(`when given ${contentType}`, () => {16 assert.isFalse(isJsonContentType(contentType));17 });18 });19 it('when given rubbish', () => {20 assert.isFalse(isJsonContentType('foo'));21 });22 });...
jsonLens.js
Source:jsonLens.js
1import { isJSONContentType } from "../utils/contenttypes";2const jsonLens = {3 lensName: "JSON",4 isSupportedContentType: isJSONContentType,5 renderer: "json",6 rendererImport: () => import("~/components/lenses/renderers/JSONLensRenderer"),7}...
Using AI Code Generation
1const { isJsonContentType } = require('playwright/lib/utils/utils');2console.log(isJsonContentType('application/json'));3console.log(isJsonContentType('application/json; charset=utf-8'));4console.log(isJsonContentType('application/json; charset=utf-8;'));5console.log(isJsonContentType('application/json; charset=utf-8; foo=bar'));6console.log(isJsonContentType('application/json; charset=utf-8; foo=bar;'));7console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux'));8console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux;'));9console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo'));10console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo;'));11console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo; baz=qux'));12console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo; baz=qux;'));13console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo; baz=qux; foo=bar'));14console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo; baz=qux; foo=bar;'));15console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo; baz=qux; foo=bar; bar=foo'));16console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo; baz=qux; foo=bar; bar=foo;'));17console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo; baz=qux; foo=bar; bar=foo; baz=qux'));18console.log(isJsonContentType('application/json; charset=utf-8; foo=bar; baz=qux; bar=foo; baz=qux; foo=bar; bar=foo; baz=
Using AI Code Generation
1const { isJsonContentType } = require('@playwright/test/lib/utils/utils');2const { isJsonContentType } = require('@playwright/test/lib/utils/utils');3const isJson = isJsonContentType('application/json');4console.log(isJson);5const { isJsonContentType } = require('@playwright/test/lib/utils/utils');6const isJson = isJsonContentType('application/json;charset=utf-8');7console.log(isJson);8const { isJsonContentType } = require('@playwright/test/lib/utils/utils');9const isJson = isJsonContentType('application/json; charset=utf-8');10console.log(isJson);11const { isJsonContentType } = require('@playwright/test/lib/utils/utils');12const isJson = isJsonContentType('application/json; charset=utf-8');13console.log(isJson);14const { isJsonContentType } = require('@playwright/test/lib/utils/utils');15const isJson = isJsonContentType('application/json; charset=utf-8');16console.log(isJson);17const { isJsonContentType } = require('@playwright/test/lib/utils/utils');18const isJson = isJsonContentType('application/json; charset=utf-8');19console.log(isJson);20const { isJsonContentType } = require('@playwright/test/lib/utils/utils');21const isJson = isJsonContentType('application/json; charset=utf-8');22console.log(isJson);23const { isJsonContentType } = require('@playwright/test/lib/utils/utils');24const isJson = isJsonContentType('application/json; charset=utf-8');25console.log(isJson);
Using AI Code Generation
1const { isJsonContentType } = require('playwright/lib/utils/utils');2 'application/json; charset=utf-8',3 'application/json; charset=UTF-8',4 'application/json; charset=UTF-8; boundary=123',5 'application/json; boundary=123',6 'application/json; boundary=123; charset=UTF-8',7 'application/json; boundary=123; charset=utf-8',8 'application/json; boundary=123; charset=iso-8859-1',9 'application/json; boundary=123; charset=UTF-8; boundary=456',10 'application/json; boundary=123; charset=UTF-8; boundary=456; charset=iso-8859-1',11];12const isJson = contentTypes.map((contentType) => {13 return isJsonContentType(contentType);14});15console.log(isJson);
Using AI Code Generation
1const { isJsonContentType } = require('playwright/lib/utils/utils');2console.log(isJsonContentType('application/json; charset=UTF-8'));3console.log(isJsonContentType('application/json'));4const { isJsonContentType } = require('playwright/lib/utils/utils');5console.log(isJsonContentType('application/json; charset=UTF-8'));6console.log(isJsonContentType('application/json'));
Using AI Code Generation
1const { isJsonContentType } = require('playwright/lib/utils/utils');2const jsonContentType = 'application/json';3const textContentType = 'text/plain';4console.log('isJsonContentType(jsonContentType) : ', isJsonContentType(jsonContentType));5console.log('isJsonContentType(textContentType) : ', isJsonContentType(textContentType));6isJsonContentType(jsonContentType) : true7isJsonContentType(textContentType) : false
Using AI Code Generation
1const { isJsonContentType } = require('playwright/lib/utils/utils');2import { isJsonContentType } from 'playwright/lib/utils/utils';3import { isJsonContentType } from 'playwright/lib/utils/utils';4import { isJsonContentType } from 'playwright/lib/utils/utils';5import { isJsonContentType } from 'playwright/lib/utils/utils';6import { isJsonContentType } from 'playwright/lib/utils/utils';7import { isJsonContentType } from 'playwright/lib/utils/utils';8import { isJsonContentType } from 'playwright/lib/utils/utils';9import { isJsonContentType } from 'playwright/lib/utils/utils';10import { isJsonContentType } from 'playwright/lib/utils/utils';11import { isJsonContentType } from 'playwright/lib/utils/utils';12import { isJsonContentType } from 'playwright/lib/utils/utils';13const json = isJsonContentType('application/json
Using AI Code Generation
1const { isJsonContentType } = require('@playwright/test/lib/utils/utils');2const contentType = 'application/json';3console.log(isJsonContentType(contentType));4const { isJsonContentType } = require('@playwright/test/lib/utils/utils');5const contentType = 'application/json; charset=utf-8';6console.log(isJsonContentType(contentType));7const { isJsonContentType } = require('@playwright/test/lib/utils/utils');8const contentType = 'application/json; charset=utf-8';9console.log(isJsonContentType(contentType));10const { isJsonContentType } = require('@playwright/test/lib/utils/utils');11const contentType = 'application/json; charset=utf-8';12console.log(isJsonContentType(contentType));13const { isJsonContentType } = require('@playwright/test/lib/utils/utils');14const contentType = 'application/json; charset=utf-8';15console.log(isJsonContentType(contentType));16const { isJsonContentType } = require('@playwright/test/lib/utils/utils');17const contentType = 'application/json; charset=utf-8';18console.log(isJsonContentType(contentType));19const { isJsonContentType } = require('@playwright/test/lib/utils/utils');20const contentType = 'application/json; charset=utf-8';21console.log(isJsonContentType(contentType));22const { isJsonContentType } = require('@playwright/test/lib/utils/utils');23const contentType = 'application/json; charset=utf-8';24console.log(isJsonContentType(contentType));25const { isJsonContentType } = require('@playwright/test/lib/utils/utils');26const contentType = 'application/json;
Using AI Code Generation
1const { isJsonContentType } = require('playwright/lib/utils/utils');2const contentType = response.headers()['content-type'];3console.log(isJsonContentType(contentType));4const contentType = response.headers()['content-type'];5console.log(isJsonContentType(contentType));6const { chromium } = require('playwright');7(async () => {8 const browser = await chromium.launch();9 const context = await browser.newContext();10 const page = await context.newPage();11 const response = await page.waitForResponse('**/todos/1');12 const contentType = response.headers()['content-type'];13 console.log(isJsonContentType(contentType));14 await browser.close();15})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!