Best JavaScript code snippet using mountebank
repository-private.ts
Source:repository-private.ts
1import * as express from "express";2import { ensureAuthenticated } from "./connection";3import * as db from "../database/database";4import { getRepo, getUser, handleError, isOwnerOrAdmin } from "./route-utils";5import { getRepositoryFromGitHub } from "../source/GitHubRepository";6import gh = require("parse-github-url");7import GitHubBase from "../source/GitHubBase";8import AnonymizedRepositoryModel from "../database/anonymizedRepositories/anonymizedRepositories.model";9import config from "../../config";10import { IAnonymizedRepositoryDocument } from "../database/anonymizedRepositories/anonymizedRepositories.types";11import Repository from "../Repository";12import ConferenceModel from "../database/conference/conferences.model";13import AnonymousError from "../AnonymousError";14import { downloadQueue, removeQueue } from "../queue";15import RepositoryModel from "../database/repositories/repositories.model";16const router = express.Router();17// user needs to be connected for all user API18router.use(ensureAuthenticated);19// claim a repository20router.post("/claim", async (req: express.Request, res: express.Response) => {21 const user = await getUser(req);22 try {23 if (!req.body.repoId) {24 throw new AnonymousError("repoId_not_defined", {25 object: req.body,26 httpStatus: 400,27 });28 }29 if (!req.body.repoUrl) {30 throw new AnonymousError("repoUrl_not_defined", {31 object: req.body,32 httpStatus: 400,33 });34 }35 const repoConfig = await db.getRepository(req.body.repoId);36 if (repoConfig == null) {37 throw new AnonymousError("repo_not_found", {38 object: req.body,39 httpStatus: 404,40 });41 }42 const r = gh(req.body.repoUrl);43 const repo = await getRepositoryFromGitHub({44 owner: r.owner,45 repo: r.name,46 accessToken: user.accessToken,47 });48 if (!repo) {49 throw new AnonymousError("repo_not_found", {50 object: req.body,51 httpStatus: 404,52 });53 }54 const dbRepo = await RepositoryModel.findById(55 (repoConfig.source as GitHubBase).githubRepository.id56 );57 if (!dbRepo || dbRepo.externalId != repo.id) {58 throw new AnonymousError("repo_not_found", {59 object: req.body,60 httpStatus: 404,61 });62 }63 console.log(`${user.username} claims ${r.repository}.`);64 repoConfig.owner = user;65 await AnonymizedRepositoryModel.updateOne(66 { repoId: repoConfig.repoId },67 { $set: { owner: user.model.id } }68 );69 return res.send("Ok");70 } catch (error) {71 handleError(error, res, req);72 }73});74// refresh repository75router.post(76 "/:repoId/refresh",77 async (req: express.Request, res: express.Response) => {78 try {79 const repo = await getRepo(req, res, { nocheck: true });80 if (!repo) return;81 if (82 repo.status == "preparing" ||83 repo.status == "removing" ||84 repo.status == "expiring"85 )86 return;87 const user = await getUser(req);88 isOwnerOrAdmin([repo.owner.id], user);89 await repo.updateIfNeeded({ force: true });90 res.json({ status: repo.status });91 } catch (error) {92 handleError(error, res, req);93 }94 }95);96// delete a repository97router.delete(98 "/:repoId/",99 async (req: express.Request, res: express.Response) => {100 const repo = await getRepo(req, res, { nocheck: true });101 if (!repo) return;102 // if (repo.status == "removing") return res.json({ status: repo.status });103 try {104 if (repo.status == "removed")105 throw new AnonymousError("is_removed", {106 object: req.params.repoId,107 httpStatus: 410,108 });109 const user = await getUser(req);110 isOwnerOrAdmin([repo.owner.id], user);111 await repo.updateStatus("removing");112 await removeQueue.add(repo.repoId, repo, { jobId: repo.repoId });113 return res.json({ status: repo.status });114 } catch (error) {115 handleError(error, res, req);116 }117 }118);119router.get(120 "/:owner/:repo/",121 async (req: express.Request, res: express.Response) => {122 const user = await getUser(req);123 try {124 const repo = await getRepositoryFromGitHub({125 owner: req.params.owner,126 repo: req.params.repo,127 accessToken: user.accessToken,128 });129 res.json(repo.toJSON());130 } catch (error) {131 handleError(error, res, req);132 }133 }134);135router.get(136 "/:owner/:repo/branches",137 async (req: express.Request, res: express.Response) => {138 const user = await getUser(req);139 try {140 const repository = await getRepositoryFromGitHub({141 accessToken: user.accessToken,142 owner: req.params.owner,143 repo: req.params.repo,144 });145 return res.json(146 await repository.branches({147 accessToken: user.accessToken,148 force: req.query.force == "1",149 })150 );151 } catch (error) {152 handleError(error, res, req);153 }154 }155);156router.get(157 "/:owner/:repo/readme",158 async (req: express.Request, res: express.Response) => {159 try {160 const user = await getUser(req);161 const repo = await getRepositoryFromGitHub({162 owner: req.params.owner,163 repo: req.params.repo,164 accessToken: user.accessToken,165 });166 if (!repo) {167 throw new AnonymousError("repo_not_found", {168 object: req.params.repoId,169 httpStatus: 404,170 });171 }172 return res.send(173 await repo.readme({174 accessToken: user.accessToken,175 force: req.query.force == "1",176 branch: req.query.branch as string,177 })178 );179 } catch (error) {180 handleError(error, res, req);181 }182 }183);184// get repository information185router.get("/:repoId/", async (req: express.Request, res: express.Response) => {186 try {187 const repo = await getRepo(req, res, { nocheck: true });188 if (!repo) return;189 const user = await getUser(req);190 isOwnerOrAdmin([repo.owner.id], user);191 res.json((await db.getRepository(req.params.repoId)).toJSON());192 } catch (error) {193 handleError(error, res, req);194 }195});196function validateNewRepo(repoUpdate): void {197 const validCharacters = /^[0-9a-zA-Z\-\_]+$/;198 if (199 !repoUpdate.repoId.match(validCharacters) ||200 repoUpdate.repoId.length < 3201 ) {202 throw new AnonymousError("invalid_repoId", {203 object: repoUpdate,204 httpStatus: 400,205 });206 }207 if (!repoUpdate.source.branch) {208 throw new AnonymousError("branch_not_specified", {209 object: repoUpdate,210 httpStatus: 400,211 });212 }213 if (!repoUpdate.source.commit) {214 throw new AnonymousError("commit_not_specified", {215 object: repoUpdate,216 httpStatus: 400,217 });218 }219 if (!repoUpdate.options) {220 throw new AnonymousError("options_not_provided", {221 object: repoUpdate,222 httpStatus: 400,223 });224 }225 if (!Array.isArray(repoUpdate.terms)) {226 throw new AnonymousError("invalid_terms_format", {227 object: repoUpdate,228 httpStatus: 400,229 });230 }231 if (!/^[a-fA-F0-9]+$/.test(repoUpdate.source.commit)) {232 throw new AnonymousError("invalid_commit_format", {233 object: repoUpdate,234 httpStatus: 400,235 });236 }237}238function updateRepoModel(239 model: IAnonymizedRepositoryDocument,240 repoUpdate: any241) {242 if (repoUpdate.source.type) {243 model.source.type = repoUpdate.source.type;244 if (245 model.source.type != "GitHubStream" &&246 model.source.type != "GitHubDownload"247 ) {248 model.source.type = "GitHubStream";249 }250 }251 model.source.commit = repoUpdate.source.commit;252 model.source.branch = repoUpdate.source.branch;253 model.options = {254 terms: repoUpdate.terms,255 expirationMode: repoUpdate.options.expirationMode,256 expirationDate: repoUpdate.options.expirationDate257 ? new Date(repoUpdate.options.expirationDate)258 : null,259 update: repoUpdate.options.update,260 image: repoUpdate.options.image,261 pdf: repoUpdate.options.pdf,262 notebook: repoUpdate.options.notebook,263 link: repoUpdate.options.link,264 page: repoUpdate.options.page,265 pageSource: repoUpdate.options.pageSource,266 };267}268// update a repository269router.post(270 "/:repoId/",271 async (req: express.Request, res: express.Response) => {272 try {273 const repo = await getRepo(req, res, { nocheck: true });274 if (!repo) return;275 const user = await getUser(req);276 isOwnerOrAdmin([repo.owner.id], user);277 const repoUpdate = req.body;278 validateNewRepo(repoUpdate);279 if (repoUpdate.source.commit != repo.model.source.commit) {280 repo.model.anonymizeDate = new Date();281 repo.model.source.commit = repoUpdate.source.commit;282 await repo.remove();283 }284 updateRepoModel(repo.model, repoUpdate);285 async function removeRepoFromConference(conferenceID) {286 const conf = await ConferenceModel.findOne({287 conferenceID,288 });289 if (conf) {290 const r = conf.repositories.filter((r) => r.id == repo.model.id);291 if (r.length == 1) r[0].removeDate = new Date();292 await conf.save();293 }294 }295 if (!repoUpdate.conference) {296 // remove conference297 if (repo.model.conference) {298 await removeRepoFromConference(repo.model.conference);299 }300 } else if (repoUpdate.conference != repo.model.conference) {301 // update/add conference302 const conf = await ConferenceModel.findOne({303 conferenceID: repoUpdate.conference,304 });305 if (conf) {306 if (307 new Date() < conf.startDate ||308 new Date() > conf.endDate ||309 conf.status !== "ready"310 ) {311 throw new AnonymousError("conf_not_activated", {312 object: conf,313 httpStatus: 400,314 });315 }316 const f = conf.repositories.filter((r) => r.id == repo.model.id);317 if (f.length) {318 // the repository already referenced the conference319 f[0].addDate = new Date();320 f[0].removeDate = null;321 } else {322 conf.repositories.push({323 id: repo.model.id,324 addDate: new Date(),325 });326 }327 if (repo.model.conference) {328 await removeRepoFromConference(repo.model.conference);329 }330 await conf.save();331 }332 }333 repo.model.conference = repoUpdate.conference;334 await repo.updateStatus("preparing");335 res.json({ status: repo.status });336 await downloadQueue.add(repo.repoId, repo, { jobId: repo.repoId });337 } catch (error) {338 return handleError(error, res, req);339 }340 }341);342// add repository343router.post("/", async (req: express.Request, res: express.Response) => {344 const user = await getUser(req);345 const repoUpdate = req.body;346 try {347 validateNewRepo(repoUpdate);348 const r = gh(repoUpdate.fullName);349 const repository = await getRepositoryFromGitHub({350 accessToken: user.accessToken,351 owner: r.owner,352 repo: r.name,353 });354 const repo = new AnonymizedRepositoryModel();355 repo.repoId = repoUpdate.repoId;356 repo.anonymizeDate = new Date();357 repo.owner = user.id;358 updateRepoModel(repo, repoUpdate);359 repo.source.accessToken = user.accessToken;360 repo.source.repositoryId = repository.model.id;361 repo.source.repositoryName = repoUpdate.fullName;362 if (repo.source.type == "GitHubDownload") {363 // details.size is in kilobytes364 if (repository.size > config.MAX_REPO_SIZE) {365 throw new AnonymousError("invalid_mode", {366 object: repository,367 httpStatus: 400,368 });369 }370 }371 if (repository.size < config.AUTO_DOWNLOAD_REPO_SIZE) {372 repo.source.type = "GitHubDownload";373 }374 repo.conference = repoUpdate.conference;375 await repo.save();376 if (repoUpdate.conference) {377 const conf = await ConferenceModel.findOne({378 conferenceID: repoUpdate.conference,379 });380 if (conf) {381 if (382 new Date() < conf.startDate ||383 new Date() > conf.endDate ||384 conf.status !== "ready"385 ) {386 await repo.remove();387 throw new AnonymousError("conf_not_activated", {388 object: conf,389 httpStatus: 400,390 });391 }392 conf.repositories.push({393 id: repo.id,394 addDate: new Date(),395 });396 await conf.save();397 }398 }399 res.send({ status: repo.status });400 downloadQueue.add(repo.repoId, new Repository(repo), {401 jobId: repo.repoId,402 attempts: 3,403 });404 } catch (error) {405 if (error.message?.indexOf(" duplicate key") > -1) {406 return handleError(407 new AnonymousError("repoId_already_used", {408 httpStatus: 400,409 cause: error,410 object: repoUpdate,411 }),412 res,413 req414 );415 }416 return handleError(error, res, req);417 }418});...
deployment.js
Source:deployment.js
1/**2 * @license3 * Copyright 2016 Squarespace, INC.4 *5 * Licensed under the Apache License, Version 2.0 (the "License");6 * you may not use this file except in compliance with the License.7 * You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17/**18 * Utilities for deploying a squarespace template. Uses git under the hood.19 */20const git = require('git-cli');21const path = require('path');22const fs = require('fs-extra');23const URL = require('url-parse');24/**25 * Utility to resolve git async action, throwing error if needed.26 */27function finishWithGitResult(repo, resolve, reject, failMsg) {28 return (err) => {29 if (err) {30 reject(failMsg ? new Error(failMsg) : err);31 } else {32 resolve(repo);33 }34 };35}36/**37 * Validates and converts a repo URL into a suitable name for a git remote.38 * @param {string} url - The git repo URL39 * @return {string} the git remote name40 */41function gitUrlToOriginName(url) {42 const parsed = new URL(url);43 const badProto = parsed.protocol !== 'https:';44 const badPath = parsed.pathname !== '/template.git';45 const badPort = parsed.port !== '';46 if (badProto || badPath || badPort) {47 throw new Error(`Invalid Squarespace git URL: ${url}.`);48 }49 return parsed.hostname;50}51/**52 * Utilities for deploying templates using git.53 */54const Deployment = {55 /**56 * Attempts to open a git repo at the given path.57 * @param {string} repoPath - the folder containing the .git folder.58 * @return {Promise} a promise to return a git repo.59 */60 openRepo(repoPath) {61 const fullpath = path.resolve(repoPath, '.git');62 return Promise.resolve().then(() => {63 console.log('Opening repository...');64 try {65 const stat = fs.statSync(fullpath);66 if (!stat.isDirectory()) {67 throw '';68 }69 } catch (e) {70 throw new Error('No .git repository found');71 }72 return new git.Repository(fullpath);73 });74 },75 /**76 * Clones a repo if it exists.77 * @param {string} repoPath - the folder containing a .git folder.78 * @param {string} repoUrl - the git URL for the repo.79 * @return {Promise} a promise to return a git repo.80 */81 cloneRepo(repoPath, repoUrl) {82 console.log('Trying to clone...');83 return new Promise((resolve, reject) => {84 try {85 git.Repository.clone(repoUrl, repoPath, (err, repo) => {86 if (err) {87 const errmsg = 'Couldn\'t clone. Please ensure that the URL ' +88 'points to a valid Squarespace GIT repository.';89 reject(new Error(errmsg));90 } else {91 resolve(repo);92 }93 });94 }95 catch (e) {96 reject(e);97 }98 });99 },100 /**101 * Initializes a repository from scratch.102 * @param {string} repoPath - the folder containing a .git folder.103 * @return {Promise} a promise to return a git repo.104 */105 initRepo(repoPath) {106 console.log('Trying to create new repo...');107 return new Promise((resolve, reject) => {108 try {109 git.Repository.init(repoPath, (err, repo) => {110 if (err) {111 reject(new Error('Couldn\'t create new git repository.'));112 } else {113 resolve(repo);114 }115 });116 } catch (e) {117 reject(e);118 }119 });120 },121 /**122 * Adds a remote.123 * @param {object} repo - a git repo.124 * @param {string} repoUrl - the git URL for the repo.125 * @return {Promise} a promise to return a git repo.126 */127 addRemote(repo, repoUrl) {128 console.log('Adding remote...');129 return new Promise((resolve, reject) => {130 try {131 const remote = gitUrlToOriginName(repoUrl);132 repo.addRemote(remote, repoUrl, (err) => {133 if (err) {134 reject(new Error('Couldn\'t set remote of new repo.'));135 } else {136 resolve(repo);137 }138 });139 } catch (e) {140 reject(e);141 }142 });143 },144 /**145 * Checks to see if repo has a remote for the given URL.146 * @param {object} repo - a git repo.147 * @param {string} repoUrl - the git URL for the repo.148 * @return {Promise} a promised boolean value.149 */150 hasRemote(repo, repoUrl) {151 return new Promise((resolve, reject) => {152 try {153 const remote = gitUrlToOriginName(repoUrl);154 repo.listRemotes((err, remotes) => {155 if (remotes.includes(remote)) {156 resolve(true);157 } else {158 resolve(false);159 }160 });161 } catch (e) {162 reject(e);163 }164 });165 },166 /**167 * Adds all changes in repo's working dir to build.168 * @param {object} repo - a git repo.169 * @return {Promise} a promise to return a git repo.170 */171 addBuild(repo) {172 console.log('Adding build...');173 return new Promise((resolve, reject) => {174 repo.add(['.'], {'all': ''}, finishWithGitResult(repo, resolve, reject));175 });176 },177 /**178 * Creates a commit for this build.179 * @param {object} repo - a git repo.180 * @param {string} message - a commit message describing this build.181 * @return {Promise} a promise to return a git repo.182 */183 makeBuildCommit(repo, message) {184 console.log('Committing build...');185 return new Promise((resolve, reject) => {186 repo.commit(message, {'allow-empty': true}, (err) => {187 if (err) {188 reject(err);189 } else {190 resolve(repo);191 }192 });193 });194 },195 /**196 * Pulls from the remote specified by the repo's URL.197 * @param {object} repo - a git repo.198 * @param {string} repoUrl - the git URL for the repo.199 * @return {Promise} a promise to return a git repo.200 */201 pullRemote(repo, repoUrl) {202 console.log('Pulling from remote...');203 const remote = gitUrlToOriginName(repoUrl);204 return new Promise((resolve, reject) => {205 repo.pull([remote, 'master'], {'strategy': 'ours' },206 finishWithGitResult(repo, resolve, reject));207 });208 },209 /**210 * Pushes the current build to the remote specified by the repo's URL.211 * @param {object} repo - a git repo.212 * @param {string} repoUrl - the git URL for the repo.213 * @param {object} flags - a key/value pair of flags to use during deploy.214 * @return {Promise} a promise to return a git repo.215 */216 pushBuild(repo, repoUrl, flags) {217 console.log('Pushing build...');218 const remote = gitUrlToOriginName(repoUrl);219 return new Promise((resolve, reject) => {220 repo.push([remote, 'master'], flags, finishWithGitResult(repo, resolve, reject));221 });222 },223 /**224 * Opens or creates a repo, using least creative strategy.225 * @param {string} folder - path to a folder containing the .git folder.226 * @param {string} repoUrl - the git URL for the repo.227 * @return {async object} a git repo.228 */229 async ensureRepo(folder, repoUrl) {230 let repo;231 try {232 repo = await Deployment.openRepo(folder);233 } catch (openError) {234 console.log('Failed to open repo.', openError.message);235 try {236 repo = await Deployment.cloneRepo(folder, repoUrl);237 } catch (cloneError) {238 console.log('Failed to clone repo.');239 try {240 repo = await Deployment.initRepo(folder);241 } catch (initError) {242 console.log('Failed to initialize repo.', initError.message);243 return null;244 }245 }246 }247 return repo;248 },249 /**250 * Checks for the remote, creates if missing.251 * @param {object} repo - a git repo.252 * @param {string} repoUrl - the git URL for the repo.253 * @return {async object} a git repo.254 */255 async ensureRemote(repo, repoUrl) {256 try {257 if (!await Deployment.hasRemote(repo, repoUrl)) {258 await Deployment.addRemote(repo, repoUrl);259 }260 } catch (error) {261 console.log('Failed to add remote.', error);262 return null;263 }264 return repo;265 },266 /**267 * Creates a build commit and pushes it to the repo.268 * @param {object} repo - a git repo.269 * @param {string} repoUrl - the git URL for the repo.270 * @param {string} buildMessage - a commit message for the build.271 * @param {object} flags - a key/value pair of flags to use during deploy.272 * @return {async object} a git repo.273 */274 async commitBuild(repo, repoUrl, buildMessage, flags) {275 try {276 await Deployment.addBuild(repo);277 await Deployment.makeBuildCommit(repo, buildMessage);278 if (!flags.force) {279 await Deployment.pullRemote(repo, repoUrl);280 }281 await Deployment.pushBuild(repo, repoUrl, flags);282 } catch (error) {283 console.error('Failed to deploy build. ' +284 'Please ensure that your site is in dev mode.');285 console.error(error.message);286 return null;287 }288 return repo;289 },290 /**291 * Deploys a template using git.292 * @param {string} folder - path to a folder containing the .git folder.293 * @param {string} url - the git URL for the repo.294 * @param {string} buildMessage - a commit message for the build.295 * @param {boolean} ensureRemote - create remote if not already there.296 * @param {object} flags - a key/value pair of flags to use during deploy.297 */298 async deploy(folder, url, buildMessage, ensureRemote, flags = {}) {299 const noCredsUrl = url.replace(/(\/\/).*?:.*?@/, '$1');300 console.log(`Deploying files in ${folder} to ${noCredsUrl}...`);301 let repo = await Deployment.ensureRepo(folder, url);302 if (!repo) {303 throw new Error('No repo!');304 }305 if (ensureRemote) {306 repo = await Deployment.ensureRemote(repo, url);307 if (!repo) {308 throw new Error('No repo!');309 }310 }311 repo = await Deployment.commitBuild(repo, url, buildMessage, flags);312 if (!repo) {313 throw new Error('No repo!');314 }315 console.log('Success!');316 }317};...
repository-public.ts
Source:repository-public.ts
1import { promisify } from "util";2import * as express from "express";3import * as stream from "stream";4import config from "../../config";5import { getRepo, handleError } from "./route-utils";6import AnonymousError from "../AnonymousError";7import { downloadQueue } from "../queue";8const router = express.Router();9router.get(10 "/:repoId/zip",11 async (req: express.Request, res: express.Response) => {12 const pipeline = promisify(stream.pipeline);13 try {14 if (!config.ENABLE_DOWNLOAD) {15 throw new AnonymousError("download_not_enabled", {16 httpStatus: 403,17 object: req.params.repoId,18 });19 }20 const repo = await getRepo(req, res);21 if (!repo) return;22 let download = false;23 const conference = await repo.conference();24 if (conference) {25 download =26 conference.quota.size > -1 &&27 !!config.ENABLE_DOWNLOAD &&28 repo.source.type == "GitHubDownload";29 }30 if (31 repo.size.storage < config.FREE_DOWNLOAD_REPO_SIZE * 1024 &&32 repo.source.type == "GitHubDownload"33 ) {34 download = true;35 }36 if (!download) {37 throw new AnonymousError("download_not_enabled", {38 httpStatus: 403,39 object: req.params.repoId,40 });41 }42 res.attachment(`${repo.repoId}.zip`);43 // cache the file for 6 hours44 res.header("Cache-Control", "max-age=21600");45 await pipeline(repo.zip(), res);46 } catch (error) {47 handleError(error, res, req);48 }49 }50);51router.get(52 "/:repoId/files",53 async (req: express.Request, res: express.Response) => {54 const repo = await getRepo(req, res);55 if (!repo) return;56 try {57 res.header("Cache-Control", "no-cache");58 res.json(await repo.anonymizedFiles({ includeSha: false }));59 } catch (error) {60 handleError(error, res, req);61 }62 }63);64router.get(65 "/:repoId/options",66 async (req: express.Request, res: express.Response) => {67 try {68 const repo = await getRepo(req, res, { nocheck: true });69 if (!repo) return;70 let redirectURL = null;71 if (72 repo.status == "expired" &&73 repo.options.expirationMode == "redirect" &&74 repo.source.url75 ) {76 redirectURL = repo.source.url;77 } else {78 if (79 repo.status == "expired" ||80 repo.status == "expiring" ||81 repo.status == "removing" ||82 repo.status == "removed"83 ) {84 throw new AnonymousError("repository_expired", {85 object: repo,86 httpStatus: 410,87 });88 }89 const fiveMinuteAgo = new Date();90 fiveMinuteAgo.setMinutes(fiveMinuteAgo.getMinutes() - 5);91 if (repo.status != "ready") {92 if (93 repo.model.statusDate < fiveMinuteAgo94 // && repo.status != "preparing"95 ) {96 await repo.updateStatus("preparing");97 await downloadQueue.add(repo.repoId, repo, {98 jobId: repo.repoId,99 attempts: 3,100 });101 }102 if (repo.status == "error") {103 throw new AnonymousError(104 repo.model.statusMessage105 ? repo.model.statusMessage106 : "repository_not_available",107 {108 object: repo,109 httpStatus: 500,110 }111 );112 }113 throw new AnonymousError("repository_not_ready", {114 httpStatus: 404,115 object: repo,116 });117 }118 await repo.updateIfNeeded();119 }120 let download = false;121 const conference = await repo.conference();122 if (conference) {123 download =124 conference.quota.size > -1 &&125 !!config.ENABLE_DOWNLOAD &&126 repo.source.type == "GitHubDownload";127 }128 if (129 repo.size.storage < config.FREE_DOWNLOAD_REPO_SIZE * 1024 &&130 repo.source.type == "GitHubDownload"131 ) {132 download = true;133 }134 res.header("Cache-Control", "no-cache");135 res.json({136 url: redirectURL,137 download,138 lastUpdateDate: repo.model.statusDate,139 });140 } catch (error) {141 handleError(error, res, req);142 }143 }144);...
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var protocol = 'http';4var host = 'localhost';5var imposter = {6 {7 {8 is: {9 }10 }11 }12};13mb.create().then(function (mbServer) {14 return mbServer.post('/imposters', imposter);15}).then(function () {16});17var mb = require('mountebank');18var port = 2525;19var protocol = 'http';20var host = 'localhost';21var imposter = {22 {23 {24 is: {25 }26 }27 }28};29mb.create().then(function (mbServer) {30 return mbServer.post('/imposters', imposter);31}).then(function () {32});33var mb = require('mountebank');34var port = 2525;35var protocol = 'http';36var host = 'localhost';37var imposter = {38 {39 {40 is: {41 }42 }43 }44};45mb.create().then(function (mbServer) {46 return mbServer.post('/imposters', imposter);47}).then(function () {48});49var mb = require('mountebank');50var port = 2525;51var protocol = 'http';52var host = 'localhost';53var imposter = {54 {
Using AI Code Generation
1const mb = require('mountebank');2const path = require('path');3const fs = require('fs');4const port = 2525;5const protocol = 'http';6const host = 'localhost';7const imposter = {8 {9 {10 equals: {11 }12 }13 {14 is: {15 headers: {16 },17 body: JSON.stringify({18 })19 }20 }21 }22};23mb.create(url, imposter)24 .then(() => {25 console.log(`Created imposter on port ${imposter.port}`);26 return mb.get(url, imposter.port);27 })28 .then(response => {29 console.log(`Imposter state: ${JSON.stringify(response.body)}`);30 return mb.del(url, imposter.port);31 })32 .then(() => {33 console.log(`Deleted imposter on port ${imposter.port}`);34 })35 .catch(error => {36 console.error(`Error creating imposter: ${error.message}`);37 });38{39 "dependencies": {40 },41 "devDependencies": {},42 "scripts": {43 },44}45curl -X POST -H "Content-Type: application/json" -d " { "port": 3000, "
Using AI Code Generation
1var mb = require('mountebank');2var request = require('request');3var chai = require('chai');4var expect = chai.expect;5var chaiAsPromised = require('chai-as-promised');6chai.use(chaiAsPromised);7var chaiHttp = require('chai-http');8chai.use(chaiHttp);9var chaiJsonSchema = require('chai-json-schema');10chai.use(chaiJsonSchema);11var chaiThings = require('chai-things');12chai.use(chaiThings);13var chaiXml = require('chai-xml');14chai.use(chaiXml);15var chaiFs = require('chai-fs');16chai.use(chaiFs);17var chaiJquery = require('chai-jquery');18chai.use(chaiJquery);19var chaiEnzyme = require('chai-enzyme');20chai.use(chaiEnzyme);21var chaiArrays = require('chai-arrays');22chai.use(chaiArrays);23var chaiDatetime = require('chai-datetime');24chai.use(chaiDatetime);25var chaiUuid = require('chai-uuid');26chai.use(chaiUuid);27var chaiXml = require('chai-xml');28chai.use(chaiXml);29var chaiLike = require('chai-like');30chai.use(chaiLike);31var chaiString = require('chai-string');32chai.use(chaiString);33var chaiSubset = require('chai-subset');34chai.use(chaiSubset);35var chaiInteger = require('chai-integer');36chai.use(chaiInteger);
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var mbServer = mb.create(port);4mbServer.start();5mbServer.createImposter({6});7var mb = require('mountebank');8var port = 2525;9var mbServer = mb.create(port);10mbServer.start();11mbServer.createImposter({12});13mbServer.get('/imposters', function (err, response) {14 console.log(response.body);15});16mbServer.get('/imposters/3000', function (err, response) {17 console.log(response.body);18});19mbServer.get('/imposters/3000/requests', function (err, response) {20 console.log(response.body);21});22mbServer.get('/imposters/3000/requests/1', function (err, response) {23 console.log(response.body);24});25mbServer.get('/imposters/3000/responses', function (err, response) {26 console.log(response.body);27});28mbServer.get('/imposters/3000/responses/1', function (err, response) {29 console.log(response.body);30});31mbServer.get('/imposters/3000/responses/1/body', function (err, response) {32 console.log(response.body);33});34mbServer.get('/imposters/3000/responses/1/headers', function (err, response) {35 console.log(response.body);36});37mbServer.get('/imposters/3000/responses/1/statusCode', function (err, response) {38 console.log(response.body);39});40mbServer.put('/imposters/3000', {41 {42 {43 is: {44 headers: {45 },46 }47 }48 }49}, function (err, response) {50 console.log(response.body);51});52mbServer.delete('/imposters/3000', function (err, response) {53 console.log(response.body);54});55mbServer.delete('/imposters', function (err, response) {56 console.log(response
Using AI Code Generation
1var mb = require('mountebank');2var repo = mb.createRepo();3repo.add({ port: 2525, stubs: [{ responses: [{ is: { body: 'Hello, world!' } }] }] }, function () {4 console.log('Imposter created');5});6var mb = require('mountebank');7mb.start({ port: 2525, stubs: [{ responses: [{ is: { body: 'Hello, world!' } }] }] }, function () {8 console.log('Imposter created');9});
Using AI Code Generation
1var mb = require('mountebank');2var fs = require('fs');3var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf8'));4{5 {6 {7 "is": {8 "headers": {9 },10 "body": {11 }12 }13 }14 }15}16describe('Mountebank Test', () => {17 it('Should return hello world', () => {18 expect(response.status).to.eq(200);19 expect(response.body.message).to.eq('Hello World');20 });21 });22});
Using AI Code Generation
1var mb = require('mountebank');2var fs = require('fs');3var path = require('path');4var api = require('./api.js');5var config = {6};7var protocol = {8 {9 {10 equals: {11 }12 }13 {14 is: {15 headers: {16 },17 body: JSON.stringify({18 })19 }20 }21 }22};23fs.writeFileSync(path.join(__dirname, config.protofile), JSON.stringify(protocol, null, 2));24mb.start(config, function (error) {25 if (error) {26 console.error(error);27 }28 else {29 console.log('Mountebank started');30 api.getTest(function (error, response, body) {31 if (error) {32 console.error(error);33 }34 else {35 console.log('Response received');36 console.log(body);37 }38 mb.stop(config, function (error) {39 if (error) {40 console.error(error);41 }42 else {43 console.log('Mountebank stopped');44 }45 });46 });47 }48});49var request = require('request');50var getTest = function (callback) {51};52module.exports = {53};54var mb = require('mountebank');
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const repoPath = './imposters';4const logger = console;5mb.start({port, repoPath, logger}, (error, server) => {6 if (error) {7 logger.error(error);8 process.exit(1);9 }10 logger.info(`mountebank server started on port ${server.port}`);11});12{13 {14 {15 "is": {16 "headers": {17 },18 }19 }20 }21}
Using AI Code Generation
1const mb = require('mountebank');2const { createImposter, createStub, createResponse, createPredicate, createEquals } = mb;3const { createRepository } = mb;4const imposter = createImposter({5});6const stub = createStub({7 createResponse({8 is: {9 }10 })11});12imposter.addStub(stub);13const predicate = createPredicate({14 equals: createEquals({15 })16});17stub.addPredicate(predicate);18repo.addImposter(imposter);19repo.save().then(() => {20 console.log('Imposter saved!');21});22const mb = require('mountebank');23const { createImposter, createStub, createResponse, createPredicate, createEquals } = mb;24const { createCommand } = mb;25const imposter = createImposter({26});27const stub = createStub({28 createResponse({29 is: {30 }31 })32});33imposter.addStub(stub);34const predicate = createPredicate({35 equals: createEquals({36 })37});38stub.addPredicate(predicate);39const command = createCommand({40});41 console.log('Imposter saved!');42});
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!!