Best JavaScript code snippet using stryker-parent
FilesRouter.js
Source:FilesRouter.js
1import express from 'express';2import BodyParser from 'body-parser';3import * as Middlewares from '../middlewares';4import Parse from 'parse/node';5import Config from '../Config';6import mime from 'mime';7import logger from '../logger';8const triggers = require('../triggers');9const http = require('http');10const downloadFileFromURI = uri => {11 return new Promise((res, rej) => {12 http13 .get(uri, response => {14 response.setDefaultEncoding('base64');15 let body = `data:${response.headers['content-type']};base64,`;16 response.on('data', data => (body += data));17 response.on('end', () => res(body));18 })19 .on('error', e => {20 rej(`Error downloading file from ${uri}: ${e.message}`);21 });22 });23};24const addFileDataIfNeeded = async file => {25 if (file._source.format === 'uri') {26 const base64 = await downloadFileFromURI(file._source.uri);27 file._previousSave = file;28 file._data = base64;29 file._requestTask = null;30 }31 return file;32};33export class FilesRouter {34 expressRouter({ maxUploadSize = '20Mb' } = {}) {35 var router = express.Router();36 router.get('/files/:appId/:filename', this.getHandler);37 router.get('/files/:appId/metadata/:filename', this.metadataHandler);38 router.post('/files', function (req, res, next) {39 next(new Parse.Error(Parse.Error.INVALID_FILE_NAME, 'Filename not provided.'));40 });41 router.post(42 '/files/:filename',43 BodyParser.raw({44 type: () => {45 return true;46 },47 limit: maxUploadSize,48 }), // Allow uploads without Content-Type, or with any Content-Type.49 Middlewares.handleParseHeaders,50 this.createHandler51 );52 router.delete(53 '/files/:filename',54 Middlewares.handleParseHeaders,55 Middlewares.enforceMasterKeyAccess,56 this.deleteHandler57 );58 return router;59 }60 getHandler(req, res) {61 const config = Config.get(req.params.appId);62 if (!config) {63 res.status(403);64 const err = new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'Invalid application ID.');65 res.json({ code: err.code, error: err.message });66 return;67 }68 const filesController = config.filesController;69 const filename = req.params.filename;70 const contentType = mime.getType(filename);71 if (isFileStreamable(req, filesController)) {72 filesController.handleFileStream(config, filename, req, res, contentType).catch(() => {73 res.status(404);74 res.set('Content-Type', 'text/plain');75 res.end('File not found.');76 });77 } else {78 filesController79 .getFileData(config, filename)80 .then(data => {81 res.status(200);82 res.set('Content-Type', contentType);83 res.set('Content-Length', data.length);84 res.end(data);85 })86 .catch(() => {87 res.status(404);88 res.set('Content-Type', 'text/plain');89 res.end('File not found.');90 });91 }92 }93 async createHandler(req, res, next) {94 const config = req.config;95 const user = req.auth.user;96 const isMaster = req.auth.isMaster;97 const isLinked = user && Parse.AnonymousUtils.isLinked(user);98 if (!isMaster && !config.fileUpload.enableForAnonymousUser && isLinked) {99 next(100 new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'File upload by anonymous user is disabled.')101 );102 return;103 }104 if (!isMaster && !config.fileUpload.enableForAuthenticatedUser && !isLinked && user) {105 next(106 new Parse.Error(107 Parse.Error.FILE_SAVE_ERROR,108 'File upload by authenticated user is disabled.'109 )110 );111 return;112 }113 if (!isMaster && !config.fileUpload.enableForPublic && !user) {114 next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'File upload by public is disabled.'));115 return;116 }117 const filesController = config.filesController;118 const { filename } = req.params;119 const contentType = req.get('Content-type');120 if (!req.body || !req.body.length) {121 next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'Invalid file upload.'));122 return;123 }124 const error = filesController.validateFilename(filename);125 if (error) {126 next(error);127 return;128 }129 const base64 = req.body.toString('base64');130 const file = new Parse.File(filename, { base64 }, contentType);131 const { metadata = {}, tags = {} } = req.fileData || {};132 file.setTags(tags);133 file.setMetadata(metadata);134 const fileSize = Buffer.byteLength(req.body);135 const fileObject = { file, fileSize };136 try {137 // run beforeSaveFile trigger138 const triggerResult = await triggers.maybeRunFileTrigger(139 triggers.Types.beforeSave,140 fileObject,141 config,142 req.auth143 );144 let saveResult;145 // if a new ParseFile is returned check if it's an already saved file146 if (triggerResult instanceof Parse.File) {147 fileObject.file = triggerResult;148 if (triggerResult.url()) {149 // set fileSize to null because we wont know how big it is here150 fileObject.fileSize = null;151 saveResult = {152 url: triggerResult.url(),153 name: triggerResult._name,154 };155 }156 }157 // if the file returned by the trigger has already been saved skip saving anything158 if (!saveResult) {159 // if the ParseFile returned is type uri, download the file before saving it160 await addFileDataIfNeeded(fileObject.file);161 // update fileSize162 const bufferData = Buffer.from(fileObject.file._data, 'base64');163 fileObject.fileSize = Buffer.byteLength(bufferData);164 // prepare file options165 const fileOptions = {166 metadata: fileObject.file._metadata,167 };168 // some s3-compatible providers (DigitalOcean, Linode) do not accept tags169 // so we do not include the tags option if it is empty.170 const fileTags =171 Object.keys(fileObject.file._tags).length > 0 ? { tags: fileObject.file._tags } : {};172 Object.assign(fileOptions, fileTags);173 // save file174 const createFileResult = await filesController.createFile(175 config,176 fileObject.file._name,177 bufferData,178 fileObject.file._source.type,179 fileOptions180 );181 // update file with new data182 fileObject.file._name = createFileResult.name;183 fileObject.file._url = createFileResult.url;184 fileObject.file._requestTask = null;185 fileObject.file._previousSave = Promise.resolve(fileObject.file);186 saveResult = {187 url: createFileResult.url,188 name: createFileResult.name,189 };190 }191 // run afterSaveFile trigger192 await triggers.maybeRunFileTrigger(triggers.Types.afterSave, fileObject, config, req.auth);193 res.status(201);194 res.set('Location', saveResult.url);195 res.json(saveResult);196 } catch (e) {197 logger.error('Error creating a file: ', e);198 const error = triggers.resolveError(e, {199 code: Parse.Error.FILE_SAVE_ERROR,200 message: `Could not store file: ${fileObject.file._name}.`,201 });202 next(error);203 }204 }205 async deleteHandler(req, res, next) {206 try {207 const { filesController } = req.config;208 const { filename } = req.params;209 // run beforeDeleteFile trigger210 const file = new Parse.File(filename);211 file._url = filesController.adapter.getFileLocation(req.config, filename);212 const fileObject = { file, fileSize: null };213 await triggers.maybeRunFileTrigger(214 triggers.Types.beforeDelete,215 fileObject,216 req.config,217 req.auth218 );219 // delete file220 await filesController.deleteFile(req.config, filename);221 // run afterDeleteFile trigger222 await triggers.maybeRunFileTrigger(223 triggers.Types.afterDelete,224 fileObject,225 req.config,226 req.auth227 );228 res.status(200);229 // TODO: return useful JSON here?230 res.end();231 } catch (e) {232 logger.error('Error deleting a file: ', e);233 const error = triggers.resolveError(e, {234 code: Parse.Error.FILE_DELETE_ERROR,235 message: 'Could not delete file.',236 });237 next(error);238 }239 }240 async metadataHandler(req, res) {241 try {242 const config = Config.get(req.params.appId);243 const { filesController } = config;244 const { filename } = req.params;245 const data = await filesController.getMetadata(filename);246 res.status(200);247 res.json(data);248 } catch (e) {249 res.status(200);250 res.json({});251 }252 }253}254function isFileStreamable(req, filesController) {255 return req.get('Range') && typeof filesController.adapter.handleFileStream === 'function';...
index.js
Source:index.js
1import $rdf from 'rdflib';2import SolidAuthing from 'solid-authing';3import SolidFileClient from './solid-file-client.js';4import solid from 'solid-auth-client';5var SolidIPFS = function(options) {6 this.$rdf = $rdf;7 this.options = options;8 this.solidAuthing = null;9 if (this.options.clientId && this.options.secret) {10 this.solidAuthing = new SolidAuthing({11 clientId: options.clientId,12 secret: options.secret,13 });14 } else {15 this.initInstance();16 }17 this.fileClient = new SolidFileClient();18 this.IPFSFolderName = 'ipfs';19 this.IPFSHashFolderName = 'hash';20 this.IPFSTopFolder = `${this.options.url}${this.IPFSFolderName}/`;21 this.IPFSHashFolder = `${this.IPFSTopFolder}${this.IPFSHashFolderName}/`;22}23SolidIPFS.prototype = {24 async initInstance() {25 if (this.solidAuthing) {26 this.solidAuth = await this.solidAuthing.getAuthingInsatance(); //å¿
é¡»è°ç¨27 } else {28 this.solidAuth = solid;29 }30 },31 async checkIPFSFolderExists(folderName) {32 const exists = await this.fileClient.readFolder(folderName);33 return exists;34 },35 async createIPFSFolder() {36 const topFolderExists = await this.checkIPFSFolderExists(this.IPFSTopFolder);37 const hashFolderExists = await this.checkIPFSFolderExists(this.IPFSHashFolder);38 if (topFolderExists && hashFolderExists) {39 return true;40 }41 if (!topFolderExists) {42 const topFolderCreateResult = await this.fileClient.createFolder(this.IPFSTopFolder);43 if (!topFolderCreateResult) {44 return false;45 } else {46 const hashFolderCreateResult = await this.fileClient.createFolder(this.IPFSHashFolder);47 return hashFolderCreateResult;48 }49 } else {50 if (hashFolderExists) {51 return true;52 } else {53 const hashFolderCreateResult = await this.fileClient.createFolder(this.IPFSHashFolder);54 return hashFolderCreateResult;55 }56 }57 },58 async storeHash(options) {59 if (!options.hash) {60 throw "请æä¾ hash å¼";61 }62 if (!this.options.url) {63 throw "请æä¾ url";64 }65 await this.solidAuth.login();66 const exists = await this.checkIPFSFolderExists();67 let createFileResult = null;68 if (exists) {69 createFileResult = await this.fileClient.createFile(`${this.IPFSHashFolder}${options.hash}.txt`, 'text/plain', options.hash);70 } else {71 const createResult = await this.createIPFSFolder();72 if (createResult) {73 createFileResult = await this.fileClient.createFile(`${this.IPFSHashFolder}${options.hash}.txt`, 'text/plain', options.hash);74 } else {75 return false;76 }77 }78 return createFileResult;79 },80}81if (typeof window === 'object') {82 window.SolidIPFS = SolidIPFS;83}...
CreateFileGroupResult.ts
Source:CreateFileGroupResult.ts
1import { CreateFileResult } from './CreateFileResult';2export interface CreateFileGroupResult {3 groupResult: CreateFileResult[];4 totalFileSize: number;...
Using AI Code Generation
1const { createFileResult } = require('stryker-parent');2const fileResult = createFileResult({3 content: 'console.log("Hello world");'4});5console.log(fileResult);6console.log('Hello world');7const test = require('./test');
Using AI Code Generation
1const createFileResult = require('stryker-parent').createFileResult;2module.exports = function (strykerConfig) {3 return function (files) {4 return Promise.resolve(files.map(file => createFileResult(file, 'some content')));5 };6};
Using AI Code Generation
1const { createFileResult } = require('stryker-parent');2module.exports = function (strykerConfig) {3 return {4 onMutationTestReportReady: function (report) {5 const fileResult = createFileResult('test.js', '1+1', '2');6 report.files.push(fileResult);7 }8 }9}
Using AI Code Generation
1const { createFileResult } = require('stryker-parent');2module.exports = function(strykerConfig) {3 return {4 onMutationTestReportReady: function (report) {5 const fileResult = createFileResult('test.js', 'dead code', 1);6 }7 };8};9const { createFileResult } = require('stryker-parent');10const fileResult = createFileResult('test.js', 'dead code', 1);11const { createMutantResult } = require('stryker-parent');12const mutantResult = createMutantResult('dead code', 1, 'true', 'NoCoverage');13const { createSourceFile } = require('stryker-parent');14const sourceFile = createSourceFile('test.js', 'const foo = 1;');15const { createMutant } = require('stryker-parent');16const mutant = createMutant('dead code', 1, 'true');17const { createMutantScoreResult } = require('stryker-parent');18const mutantScoreResult = createMutantScoreResult(100, 1, 0, 0);19const { createMetricsResult } = require('stryker-parent');20const metricsResult = createMetricsResult(100, 1, 0, 0);21const { createTestResult } = require('stryker-parent');22const testResult = createTestResult('should be true', 'Success', 0
Using AI Code Generation
1const { createFileResult } = require('stryker-parent');2module.exports = function (strykerConfig) {3 return {4 async onAllMutantsMatchedWithTests(results) {5 const fileResult = createFileResult({6 source: 'console.log("Hello world")',7 {8 location: {9 start: { line: 1, column: 15 },10 end: { line: 1, column: 28 },11 },12 },13 });14 console.log(JSON.stringify(fileResult, null, 2));15 },16 };17};18module.exports = function (config) {19 config.set({20 commandRunner: {21 },22 });23};24{25 "source": "console.log(\"Hello world\")",26 {27 "location": {28 "start": {29 },30 "end": {31 }32 },
Using AI Code Generation
1const createFileResult = require('stryker-parent').createFileResult;2createFileResult('test.js', 'passed');3createFileResult('test.js', 'timedOut');4createFileResult('test.js', 'failed');5createFileResult('test.js', 'failed', 'timedOut');6createFileResult('test.js', 'passed', 'timedOut');7createFileResult('test.js', 'passed', 'timedOut', 'failed');8createFileResult('test.js');9createFileResult('test.js', 'unknown');10createFileResult('test.js', 'unknown', 'failed');11createFileResult('test.js', 'unknown', 'failed', 'timedOut');12createFileResult('test.js', 'unknown', 'failed', 'timedOut', 'passed');13createFileResult('test.js', 'unknown', 'failed', 'timedOut', 'passed', 'survived');
Using AI Code Generation
1var createFileResult = require('stryker-parent').createFileResult;2var stryker = require('stryker');3var file = 'test.js';4 {5 }6];7var result = createFileResult(file, mutants);8console.log(result);9var createFileResult = require('stryker-parent').createFileResult;10var stryker = require('stryker');11var file = 'test.js';12 {13 }14];15var result = createFileResult(file, mutants);16console.log(result);17var createFileResult = require('stryker-parent').createFileResult;18var stryker = require('stryker');19var file = 'test.js';20 {21 }22];23var result = createFileResult(file, mutants);24console.log(result);25var createFileResult = require('stryker-parent').createFileResult;26var stryker = require('stryker');27var file = 'test.js';
Using AI Code Generation
1const createFileResult = require('stryker-parent').createFileResult;2const fileResult = createFileResult('src/subdir/file.js', 'content');3console.log(fileResult);4const createFileResult = require('stryker-parent').createFileResult;5const fileResult = createFileResult('src/subdir/file.js', 'content');6console.log(fileResult);7const createFileResult = require('stryker-parent').createFileResult;8const fileResult = createFileResult('src/subdir/file.js', 'content');9console.log(fileResult);
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!!