How to use importData method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

recipients.js

Source:recipients.js Github

copy

Full Screen

1/*2BASTAS created in Meteor. The BASTAS (Be A Santa To A Senior) application3gives operators of this program the ability to track gifts selected onlie,4gifts checked in by volunteers giving to a Senior, and delivery of the gifts5to the recipients each season.6Copyright (C) 2016 Brian McGonagill - On Behalf of the Lubbock Linux Users Group7This program is free software: you can redistribute it and/or modify8it under the terms of the GNU General Public License as published by9the Free Software Foundation, either version 3 of the License, or10(at your option) any later version.11This program is distributed in the hope that it will be useful,12but WITHOUT ANY WARRANTY; without even the implied warranty of13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14GNU General Public License for more details.15You should have received a copy of the GNU General Public License16along with this program. If not, see <http://www.gnu.org/licenses/>.17*/18import { Meteor } from 'meteor/meteor';19import { Mongo } from 'meteor/mongo';20import { check } from 'meteor/check';21export const Recipients = new Mongo.Collection('recipients');22Recipients.allow({23 insert: function(userId, doc) {24 // if user id exists, allow insert25 return !!userId;26 }27});28Meteor.methods({29 // insert a new Recipients30 'recipients.insert' (ibastasId, iroute, ifirstName, ilastName, igender, istreetAddress, icomplexName, iaptNo, icity, istate, izip, ihomePhone, icellPhone, inotes) {31 //check that the info being passed in is of the correct type32 check(ibastasId, String);33 check(iroute, String);34 check(ifirstName, String);35 check(ilastName, String);36 check(igender, String);37 check(istreetAddress, String);38 check(icomplexName, String);39 check(iaptNo, String);40 check(icity, String);41 check(istate, String);42 check(izip, String);43 check(ihomePhone, String);44 check(icellPhone, String);45 check(inotes, String);46 // make sure a user is logged in before posting the recipient info47 if (!this.userId) {48 throw new Meteor.Error('User is not authorized to add recipient information.');49 }50 // insert the recipient information to the database51 return Recipients.insert({52 bastasId: ibastasId,53 route: iroute,54 name: {55 first: ifirstName,56 last: ilastName,57 },58 gender: igender,59 address: {60 streetAddress: istreetAddress,61 complexName: icomplexName,62 aptNo: iaptNo,63 city: icity,64 state: istate,65 zip: izip,66 },67 phone: {68 home: ihomePhone,69 cell: icellPhone,70 },71 notes: inotes,72 webRecipient: false,73 webSelected: false,74 marked_Purchased: false,75 selectedBy_id: "",76 gifts: [],77 enteredBy: Meteor.user().emails[0].address,78 addedOn: new Date(),79 });80 },81 // edit a recipient82 'recipients.update' (recipientsId, ibastasId, iroute, ifirstName, ilastName, igender, istreetAddress, icomplexName, iaptNo, icity, istate, izip, ihomePhone, icellPhone, inotes) {83 //check that the info being passed in is of the correct type84 check(recipientsId, String);85 check(ibastasId, String);86 check(iroute, String);87 check(ifirstName, String);88 check(ilastName, String);89 check(igender, String);90 check(istreetAddress, String);91 check(icomplexName, String);92 check(iaptNo, String);93 check(icity, String);94 check(istate, String);95 check(izip, String);96 check(ihomePhone, String);97 check(icellPhone, String);98 check(inotes, String);99 // make sure a user is logged in before posting the recipient info100 if (!this.userId) {101 throw new Meteor.Error('User is not authorized to update recipient information.');102 }103 // update the recipient info104 Recipients.update(recipientsId, {105 $set: {106 bastasId: ibastasId,107 route: iroute,108 name: {109 first: ifirstName,110 last: ilastName,111 },112 gender: igender,113 address: {114 streetAddress: istreetAddress,115 complexName: icomplexName,116 aptNo: iaptNo,117 city: icity,118 state: istate,119 zip: izip,120 },121 phone: {122 home: ihomePhone,123 cell: icellPhone,124 },125 notes: inotes,126 editedBy: Meteor.user().emails[0].address,127 lastEditedOn: new Date(),128 }129 });130 },131 'gifts.add' (irecipientsId, igiftNo, igiftType, igiftSize, iselected, icheckedIn, ioutForDelivery, idelivered, ideliveryPerson, ideliveryPhone) {132 // check that the info being sent is what's expected133 // check that the user is logged in and has the right role134 if (!this.userId) {135 throw new Meteor.Error('User is not authorized to add gift information, or is not logged in.');136 }137 // add the gift info to the recipient138 Recipients.update(irecipientsId, {139 $addToSet: {140 gifts: {141 giftNo: igiftNo,142 giftType: igiftType,143 giftSize: igiftSize,144 selected: iselected,145 checkedIn: icheckedIn,146 outForDelivery: ioutForDelivery,147 delivered: idelivered,148 deliveryPerson: ideliveryPerson,149 deliveryPhone: ideliveryPhone,150 }151 },152 $set: {153 editedBy: Meteor.user().emails[0].address,154 lastEditedOn: new Date(),155 }156 });157 },158 'gifts.update' (irecipientsId, igiftNo, giftInfo, giftType) {159 // // console.log("made it to the update for gifts.");160 // check that the info being sent is what's expected161 check(igiftNo, Number);162 check(giftInfo, String);163 check(giftType, String);164 var giftNumber = igiftNo.toString();165 switch(giftType) {166 case "giftType":167 Recipients.update({ _id: irecipientsId, "gifts.giftNo": giftNumber }, {168 $set: {169 "gifts.$.giftType": giftInfo,170 editedBy: Meteor.user().emails[0].address,171 lastEditedOn: new Date(),172 }173 });174 break;175 case "giftSize":176 Recipients.update({ _id: irecipientsId, "gifts.giftNo": giftNumber }, {177 $set: {178 "gifts.$.giftSize": giftInfo,179 editedBy: Meteor.user().emails[0].address,180 lastEditedOn: new Date(),181 }182 });183 break;184 case "deliveryPerson":185 Recipients.update({ _id: irecipientsId, "gifts.giftNo": giftNumber }, {186 $set: {187 "gifts.$.deliveryPerson": giftInfo,188 editedBy: Meteor.user().emails[0].address,189 lastEditedOn: new Date(),190 }191 });192 break;193 case "deliveryPhone":194 Recipients.update({ _id: irecipientsId, "gifts.giftNo": giftNumber }, {195 $set: {196 "gifts.$.deliveryPhone": giftInfo,197 editedBy: Meteor.user().emails[0].address,198 lastEditedOn: new Date(),199 }200 });201 break;202 }203 },204 'Recipients.import' (importData) {205 // check the data if needed206 // check(importData, { some object });207 // *** uncomment the 2 (two) lines below to see the data being imported in the server console.208 // // console.log('--------------------------------------------------');209 // console.dir(importData);210 // ensure the user is logged in and has privileges211 if (!this.userId) {212 throw new Meteor.Error('User is not authorized to import recipient information, or is not logged in.');213 }214 // NOTE I've done the import in a bit of an ugly way...the papa-parse engine is awesome, but215 // it doesn't support having mulitple columns with the same name, so I currently am limiting216 // the gifts to 3, and having to do some fun stuff here in case there's only 1 or 2 gifts,217 // and not three on a recipient... I'm still thinking on how to improve this and simplify it in218 // the future.219 // start breaking the importData down into its parts220 for (i = 0; i < importData.data.length; i++) {221 if (!importData.data[i].giftType2 && !importData.data[i].giftType3) {222 Recipients.insert({223 bastasId: importData.data[i].bastasId,224 route: importData.data[i].route,225 name: {226 first: importData.data[i].first,227 last: importData.data[i].last,228 },229 gender: importData.data[i].gender,230 address: {231 streetAddress: importData.data[i].streetAddress,232 complexName: importData.data[i].complexName,233 aptNo: importData.data[i].aptNo,234 city: importData.data[i].city,235 state: importData.data[i].state,236 zip: importData.data[i].zip,237 },238 phone: {239 home: importData.data[i].home,240 cell: importData.data[i].cell,241 },242 gifts: [{243 giftNo: 1,244 giftType: importData.data[i].giftType1,245 giftSize: importData.data[i].giftSize1,246 selected: importData.data[i].isSelected1,247 checkedIn: importData.data[i].checkedIn1,248 outForDelivery: importData.data[i].outForDelivery1,249 delivered: importData.data[i].delivered1,250 deliveryPerson: importData.data[i].deliveryPerson1,251 deliveryPhone: importData.data[i].deliveryPhone1,252 }],253 notes: importData.data[i].notes,254 webRecipient: importData.data[i].webRecipient,255 webSelected: false,256 marked_Purchased: false,257 selectedBy_id: "",258 enteredBy: Meteor.user().emails[0].address,259 addedOn: new Date(),260 });261 } else if (importData.data[i].giftType2 && !importData.data[i].giftType3) {262 Recipients.insert({263 bastasId: importData.data[i].bastasId,264 route: importData.data[i].route,265 name: {266 first: importData.data[i].first,267 last: importData.data[i].last,268 },269 gender: importData.data[i].gender,270 address: {271 streetAddress: importData.data[i].streetAddress,272 complexName: importData.data[i].complexName,273 aptNo: importData.data[i].aptNo,274 city: importData.data[i].city,275 state: importData.data[i].state,276 zip: importData.data[i].zip,277 },278 phone: {279 home: importData.data[i].home,280 cell: importData.data[i].cell,281 },282 gifts: [{283 giftNo: 1,284 giftType: importData.data[i].giftType1,285 giftSize: importData.data[i].giftSize1,286 selected: importData.data[i].isSelected1,287 checkedIn: importData.data[i].checkedIn1,288 outForDelivery: importData.data[i].outForDelivery1,289 delivered: importData.data[i].delivered1,290 deliveryPerson: importData.data[i].deliveryPerson1,291 deliveryPhone: importData.data[i].deliveryPhone1,292 }, {293 giftNo: 2,294 giftType: importData.data[i].giftType2,295 giftSize: importData.data[i].giftSize2,296 selected: importData.data[i].isSelected2,297 checkedIn: importData.data[i].checkedIn2,298 outForDelivery: importData.data[i].outForDelivery2,299 delivered: importData.data[i].delivered2,300 deliveryPerson: importData.data[i].deliveryPerson2,301 deliveryPhone: importData.data[i].deliveryPhone2,302 }],303 notes: importData.data[i].notes,304 webRecipient: importData.data[i].webRecipient,305 webSelected: false,306 marked_Purchased: false,307 selectedBy_id: "",308 enteredBy: Meteor.user().emails[0].address,309 addedOn: new Date(),310 });311 } else {312 Recipients.insert({313 bastasId: importData.data[i].bastasId,314 route: importData.data[i].route,315 name: {316 first: importData.data[i].first,317 last: importData.data[i].last,318 },319 gender: importData.data[i].gender,320 address: {321 streetAddress: importData.data[i].streetAddress,322 complexName: importData.data[i].complexName,323 aptNo: importData.data[i].aptNo,324 city: importData.data[i].city,325 state: importData.data[i].state,326 zip: importData.data[i].zip,327 },328 phone: {329 home: importData.data[i].home,330 cell: importData.data[i].cell,331 },332 gifts: [{333 giftNo: 1,334 giftType: importData.data[i].giftType1,335 giftSize: importData.data[i].giftSize1,336 selected: importData.data[i].isSelected1,337 checkedIn: importData.data[i].checkedIn1,338 outForDelivery: importData.data[i].outForDelivery1,339 delivered: importData.data[i].delivered1,340 deliveryPerson: importData.data[i].deliveryPerson1,341 deliveryPhone: importData.data[i].deliveryPhone1,342 }, {343 giftNo: 2,344 giftType: importData.data[i].giftType2,345 giftSize: importData.data[i].giftSize2,346 selected: importData.data[i].isSelected2,347 checkedIn: importData.data[i].checkedIn2,348 outForDelivery: importData.data[i].outForDelivery2,349 delivered: importData.data[i].delivered2,350 deliveryPerson: importData.data[i].deliveryPerson2,351 deliveryPhone: importData.data[i].deliveryPhone2,352 }, {353 giftNo: 3,354 giftType: importData.data[i].giftType3,355 giftSize: importData.data[i].giftSize3,356 selected: importData.data[i].isSelected3,357 checkedIn: importData.data[i].checkedIn3,358 outForDelivery: importData.data[i].outForDelivery3,359 delivered: importData.data[i].delivered3,360 deliveryPerson: importData.data[i].deliveryPerson3,361 deliveryPhone: importData.data[i].deliveryPhone3,362 } ],363 notes: importData.data[i].notes,364 webRecipient: importData.data[i].webRecipient,365 webSelected: false,366 marked_Purchased: false,367 selectedBy_id: "",368 enteredBy: Meteor.user().emails[0].address,369 addedOn: new Date(),370 });371 }372 }373 },374 'Selected.update' (recipientId, selectedState, indexNo) {375 return Recipients.update({ _id: recipientId, "gifts.giftNo": indexNo }, {376 $set: { 'gifts.$.selected': selectedState, editedBy: Meteor.user().emails[0].address,377 lastEditedOn: new Date(), } },378 );379 },380 'CheckedIn.update' (recipientId, selectedState, indexNo) {381 return Recipients.update({ _id: recipientId, "gifts.giftNo": indexNo }, {382 $set: { 'gifts.$.checkedIn': selectedState, editedBy: Meteor.user().emails[0].address,383 lastEditedOn: new Date(), } },384 );385 },386 'OutForDelivery.update' (recipientId, selectedState, giftTypeInfo) {387 return Recipients.update({ _id: recipientId, "gifts.giftType": giftTypeInfo }, {388 $set: { 'gifts.$.outForDelivery': selectedState, editedBy: Meteor.user().emails[0].address,389 lastEditedOn: new Date(), } },390 );391 },392 'Delivered.update' (recipientId, selectedState, giftTypeInfo) {393 return Recipients.update({ _id: recipientId, "gifts.giftType": giftTypeInfo }, {394 $set: { 'gifts.$.delivered': selectedState, editedBy: Meteor.user().emails[0].address,395 lastEditedOn: new Date(), } },396 );397 },398 getGift(id, giftNo) {399 var giftsFor = Recipients.find({ _id: id, "gifts.giftNo": giftNo }, { "gifts.$": 1 });400 // // console.log(giftsFor);401 return giftsFor;402 },403 'deleteRecipient' (recipientId) {404 check(recipientId, String);405 // // console.log("--------------------------------");406 // // console.log(" User Deleted ");407 return Recipients.remove({ _id: recipientId });408 },409 'webRecip.update' (recipientId, state) {410 check(recipientId, String);411 check(state, Boolean);412 if (!this.userId) {413 throw new Meteor.Error('User is not authorized to make recipient web enabled, or is not logged in.');414 }415 if (state == true) {416 return Recipients.update({ _id: recipientId }, {417 $set: {418 webRecipient: state,419 editedBy: Meteor.user().emails[0].address,420 lastEditedOn: new Date(),421 }422 });423 } else {424 for (giftsCount = 0; giftsCount < 3; giftsCount++) {425 let giftCount = giftsCount + 1;426 Recipients.update({ _id: recipientId, "gifts.giftNo": giftCount }, {427 $set: {428 'gifts.$.selected': false,429 editedBy: Meteor.user().emails[0].address,430 lastEditedOn: new Date(), } },431 );432 }433 return Recipients.update({ _id: recipientId }, {434 $set: {435 webRecipient: state,436 webSelected: false,437 selectedBy_id: "",438 selectedBy_email: "",439 marked_Purchased: false,440 }441 });442 }443 },444 'SelectForWeb.update' (recipientIds) {445 check(recipientIds, String);446 if (!this.userId) {447 throw new Meteor.Error('User is not authorized to select a web recipient, or is not logged in.');448 }449 let recipient = Recipients.findOne({ _id: recipientIds });450 let noGifts = recipient.gifts.length;451 if (noGifts == 1) {452 Recipients.update({ _id: recipientIds, "gifts.giftNo": noGifts }, {453 $set: { 'gifts.$.selected': true } },454 );455 } else if (noGifts == 2) {456 for (j = 0; j<noGifts; j++) {457 Recipients.update({ _id: recipientIds, "gifts.giftNo": j+1 }, {458 $set: { 'gifts.$.selected': true }459 });460 }461 } else if (noGifts == 3) {462 for (k = 0; k<noGifts; k++) {463 Recipients.update({ _id: recipientIds, "gifts.giftNo": k+1 }, {464 $set: { 'gifts.$.selected': true }465 });466 }467 }468 Recipients.update({ _id: recipientIds }, {469 $set: {470 webSelected: true,471 selectedBy_id: Meteor.userId(),472 selectedBy_email: Meteor.user().emails[0].address,473 marked_Purchased: false,474 }475 });476 },477 'CompleteGifts.update' (giftsBoughtRecipId) {478 check(giftsBoughtRecipId, String);479 if (!this.userId) {480 throw new Meteor.Error('User is not authorized to update gift purchase information, or is not logged in.');481 }482 // query to see how many gifts the recipient has listed483 if (Recipients.findOne({ _id: giftsBoughtRecipId, "gifts.giftNo": 3 })) {484 var giftCount = 3;485 } else if (Recipients.findOne({ _id: giftsBoughtRecipId, "gifts.giftNo": 2 })) {486 var giftCount = 2;487 } else if (Recipients.findOne({ _id: giftsBoughtRecipId, "gifts.giftNo": 1 })) {488 var giftCount = 1489 } else {490 // console.log("No Gifts found for this recipient.");491 }492 for (g = 1; g <= giftCount; g++) {493 Recipients.update({ _id: giftsBoughtRecipId, "gifts.giftNo": g }, {494 $set: {495 "gifts.$.selected": true,496 marked_Purchased: true,497 }498 });499 }500 },501 'UnSelectRecipient' (recipientId) {502 check(recipientId, String);503 if (!this.userId) {504 throw new Meteor.Error('User is not authorized to remove a recipient from this list, or is not logged in.');505 }506 // console.log("removing for ID " + recipientId);507 // query to see how many gifts the recipient has listed508 if (Recipients.findOne({ _id: recipientId, "gifts.giftNo": 3 })) {509 // // console.log("Found three gifts");510 var removeGifts = 3;511 } else if (Recipients.findOne({ _id:recipientId, "gifts.giftNo": 2 })) {512 // // console.log("found 2 gifts");513 var removeGifts = 2;514 } else if (Recipients.findOne({ _id: recipientId, "gifts.giftNo": 1 })) {515 // // console.log("Found 1 gift.");516 var removeGifts = 1;517 } else {518 // console.log("No Gifts found for this recipient.");519 }520 for (h=0; h < removeGifts; h++) {521 // // console.log("Removing gift " + (h+1));522 Recipients.update({ _id: recipientId, "gifts.giftNo": h+1 }, {523 $set: {524 "gifts.$.selected": false,525 marked_Purchased: false,526 webSelected: false,527 selectedBy_id: "",528 }529 });530 }531 },532 "note.edit" (recipientId, noteText) {533 check(noteText, String);534 if (!this.userId) {535 throw new Meteor.Error('User is not authorized to remove a recipient from this list, or is not logged in.');536 }537 Recipients.update({ _id: recipientId}, {538 $set: {539 notes: noteText,540 editedBy: Meteor.user().emails[0].address,541 lastEditedOn: new Date(),542 }543 });544 },545 // get numbers for gift counts...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1var _ = require('lodash'),2 Promise = require('bluebird'),3 sequence = require('../../utils/sequence'),4 pipeline = require('../../utils/pipeline'),5 fs = require('fs-extra'),6 path = require('path'),7 os = require('os'),8 glob = require('glob'),9 uuid = require('node-uuid'),10 extract = require('extract-zip'),11 errors = require('../../errors'),12 ImageHandler = require('./handlers/image'),13 JSONHandler = require('./handlers/json'),14 MarkdownHandler = require('./handlers/markdown'),15 ImageImporter = require('./importers/image'),16 DataImporter = require('./importers/data'),17 // Glob levels18 ROOT_ONLY = 0,19 ROOT_OR_SINGLE_DIR = 1,20 ALL_DIRS = 2,21 defaults;22defaults = {23 extensions: ['.zip'],24 types: ['application/zip', 'application/x-zip-compressed'],25 directories: []26};27function ImportManager() {28 this.importers = [ImageImporter, DataImporter];29 this.handlers = [ImageHandler, JSONHandler, MarkdownHandler];30 // Keep track of files to cleanup at the end31 this.filesToDelete = [];32}33/**34 * A number, or a string containing a number.35 * @typedef {Object} ImportData36 * @property [Object] data37 * @property [Array] images38 */39_.extend(ImportManager.prototype, {40 /**41 * Get an array of all the file extensions for which we have handlers42 * @returns {string[]}43 */44 getExtensions: function () {45 return _.flatten(_.union(_.pluck(this.handlers, 'extensions'), defaults.extensions));46 },47 /**48 * Get an array of all the mime types for which we have handlers49 * @returns {string[]}50 */51 getTypes: function () {52 return _.flatten(_.union(_.pluck(this.handlers, 'types'), defaults.types));53 },54 /**55 * Get an array of directories for which we have handlers56 * @returns {string[]}57 */58 getDirectories: function () {59 return _.flatten(_.union(_.pluck(this.handlers, 'directories'), defaults.directories));60 },61 /**62 * Convert items into a glob string63 * @param {String[]} items64 * @returns {String}65 */66 getGlobPattern: function (items) {67 return '+(' + _.reduce(items, function (memo, ext) {68 return memo !== '' ? memo + '|' + ext : ext;69 }, '') + ')';70 },71 /**72 * @param {String[]} extensions73 * @param {Number} level74 * @returns {String}75 */76 getExtensionGlob: function (extensions, level) {77 var prefix = level === ALL_DIRS ? '**/*' :78 (level === ROOT_OR_SINGLE_DIR ? '{*/*,*}' : '*');79 return prefix + this.getGlobPattern(extensions);80 },81 /**82 *83 * @param {String[]} directories84 * @param {Number} level85 * @returns {String}86 */87 getDirectoryGlob: function (directories, level) {88 var prefix = level === ALL_DIRS ? '**/' :89 (level === ROOT_OR_SINGLE_DIR ? '{*/,}' : '');90 return prefix + this.getGlobPattern(directories);91 },92 /**93 * Remove files after we're done (abstracted into a function for easier testing)94 * @returns {Function}95 */96 cleanUp: function () {97 var filesToDelete = this.filesToDelete;98 return function (result) {99 _.each(filesToDelete, function (fileToDelete) {100 fs.remove(fileToDelete, function (err) {101 if (err) {102 errors.logError(err, 'Import could not clean up file ', 'Your blog will continue to work as expected');103 }104 });105 });106 return result;107 };108 },109 /**110 * Return true if the given file is a Zip111 * @returns Boolean112 */113 isZip: function (ext) {114 return _.contains(defaults.extensions, ext);115 },116 /**117 * Checks the content of a zip folder to see if it is valid.118 * Importable content includes any files or directories which the handlers can process119 * Importable content must be found either in the root, or inside one base directory120 *121 * @param {String} directory122 * @returns {Promise}123 */124 isValidZip: function (directory) {125 // Globs match content in the root or inside a single directory126 var extMatchesBase = glob.sync(127 this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}128 ),129 extMatchesAll = glob.sync(130 this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory}131 ),132 dirMatches = glob.sync(133 this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory}134 ),135 oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR),136 {cwd: directory});137 // This is a temporary extra message for the old format roon export which doesn't work with Ghost138 if (oldRoonMatches.length > 0) {139 throw new errors.UnsupportedMediaTypeError(140 'Your zip file looks like an old format Roon export, please re-export your Roon blog and try again.'141 );142 }143 // If this folder contains importable files or a content or images directory144 if (extMatchesBase.length > 0 || (dirMatches.length > 0 && extMatchesAll.length > 0)) {145 return true;146 }147 if (extMatchesAll.length < 1) {148 throw new errors.UnsupportedMediaTypeError('Zip did not include any content to import.');149 }150 throw new errors.UnsupportedMediaTypeError('Invalid zip file structure.');151 },152 /**153 * Use the extract module to extract the given zip file to a temp directory & return the temp directory path154 * @param {String} filePath155 * @returns {Promise[]} Files156 */157 extractZip: function (filePath) {158 var tmpDir = path.join(os.tmpdir(), uuid.v4());159 this.filesToDelete.push(tmpDir);160 return Promise.promisify(extract)(filePath, {dir: tmpDir}).then(function () {161 return tmpDir;162 });163 },164 /**165 * Use the handler extensions to get a globbing pattern, then use that to fetch all the files from the zip which166 * are relevant to the given handler, and return them as a name and path combo167 * @param {Object} handler168 * @param {String} directory169 * @returns [] Files170 */171 getFilesFromZip: function (handler, directory) {172 var globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS);173 return _.map(glob.sync(globPattern, {cwd: directory}), function (file) {174 return {name: file, path: path.join(directory, file)};175 });176 },177 /**178 * Get the name of the single base directory if there is one, else return an empty string179 * @param {String} directory180 * @returns {Promise (String)}181 */182 getBaseDirectory: function (directory) {183 // Globs match root level only184 var extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}),185 dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}),186 extMatchesAll;187 // There is no base directory188 if (extMatches.length > 0 || dirMatches.length > 0) {189 return;190 }191 // There is a base directory, grab it from any ext match192 extMatchesAll = glob.sync(193 this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory}194 );195 if (extMatchesAll.length < 1 || extMatchesAll[0].split('/') < 1) {196 throw new errors.ValidationError('Invalid zip file: base directory read failed');197 }198 return extMatchesAll[0].split('/')[0];199 },200 /**201 * Process Zip202 * Takes a reference to a zip file, extracts it, sends any relevant files from inside to the right handler, and203 * returns an object in the importData format: {data: {}, images: []}204 * The data key contains JSON representing any data that should be imported205 * The image key contains references to images that will be stored (and where they will be stored)206 * @param {File} file207 * @returns {Promise(ImportData)}208 */209 processZip: function (file) {210 var self = this;211 return this.extractZip(file.path).then(function (zipDirectory) {212 var ops = [],213 importData = {},214 baseDir;215 self.isValidZip(zipDirectory);216 baseDir = self.getBaseDirectory(zipDirectory);217 _.each(self.handlers, function (handler) {218 if (importData.hasOwnProperty(handler.type)) {219 // This limitation is here to reduce the complexity of the importer for now220 return Promise.reject(new errors.UnsupportedMediaTypeError(221 'Zip file contains multiple data formats. Please split up and import separately.'222 ));223 }224 var files = self.getFilesFromZip(handler, zipDirectory);225 if (files.length > 0) {226 ops.push(function () {227 return handler.loadFile(files, baseDir).then(function (data) {228 importData[handler.type] = data;229 });230 });231 }232 });233 if (ops.length === 0) {234 return Promise.reject(new errors.UnsupportedMediaTypeError(235 'Zip did not include any content to import.'236 ));237 }238 return sequence(ops).then(function () {239 return importData;240 });241 });242 },243 /**244 * Process File245 * Takes a reference to a single file, sends it to the relevant handler to be loaded and returns an object in the246 * importData format: {data: {}, images: []}247 * The data key contains JSON representing any data that should be imported248 * The image key contains references to images that will be stored (and where they will be stored)249 * @param {File} file250 * @returns {Promise(ImportData)}251 */252 processFile: function (file, ext) {253 var fileHandler = _.find(this.handlers, function (handler) {254 return _.contains(handler.extensions, ext);255 });256 return fileHandler.loadFile([_.pick(file, 'name', 'path')]).then(function (loadedData) {257 // normalize the returned data258 var importData = {};259 importData[fileHandler.type] = loadedData;260 return importData;261 });262 },263 /**264 * Import Step 1:265 * Load the given file into usable importData in the format: {data: {}, images: []}, regardless of266 * whether the file is a single importable file like a JSON file, or a zip file containing loads of files.267 * @param {File} file268 * @returns {Promise}269 */270 loadFile: function (file) {271 var self = this,272 ext = path.extname(file.name).toLowerCase();273 this.filesToDelete.push(file.path);274 return this.isZip(ext) ? self.processZip(file) : self.processFile(file, ext);275 },276 /**277 * Import Step 2:278 * Pass the prepared importData through the preProcess function of the various importers, so that the importers can279 * make any adjustments to the data based on relationships between it280 * @param {ImportData} importData281 * @returns {Promise(ImportData)}282 */283 preProcess: function (importData) {284 var ops = [];285 _.each(this.importers, function (importer) {286 ops.push(function () {287 return importer.preProcess(importData);288 });289 });290 return pipeline(ops);291 },292 /**293 * Import Step 3:294 * Each importer gets passed the data from importData which has the key matching its type - i.e. it only gets the295 * data that it should import. Each importer then handles actually importing that data into Ghost296 * @param {ImportData} importData297 * @returns {Promise(ImportData)}298 */299 doImport: function (importData) {300 var ops = [];301 _.each(this.importers, function (importer) {302 if (importData.hasOwnProperty(importer.type)) {303 ops.push(function () {304 return importer.doImport(importData[importer.type]);305 });306 }307 });308 return sequence(ops).then(function (importResult) {309 return importResult;310 });311 },312 /**313 * Import Step 4:314 * Report on what was imported, currently a no-op315 * @param {ImportData} importData316 * @returns {Promise(ImportData)}317 */318 generateReport: function (importData) {319 return Promise.resolve(importData);320 },321 /**322 * Import From File323 * The main method of the ImportManager, call this to kick everything off!324 * @param {File} file325 * @returns {Promise}326 */327 importFromFile: function (file) {328 var self = this;329 // Step 1: Handle converting the file to usable data330 return this.loadFile(file).then(function (importData) {331 // Step 2: Let the importers pre-process the data332 return self.preProcess(importData);333 }).then(function (importData) {334 // Step 3: Actually do the import335 // @TODO: It would be cool to have some sort of dry run flag here336 return self.doImport(importData);337 }).then(function (importData) {338 // Step 4: Report on the import339 return self.generateReport(importData)340 // Step 5: Cleanup any files341 .finally(self.cleanUp());342 });343 }344});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Pact } = require('@pact-foundation/pact');2const { somethingLike: like, term } = require('@pact-foundation/pact').Matchers;3const { importData } = require('@pact-foundation/pact-node');4const path = require('path');5const opts = {6 pactFilesOrDirs: [path.resolve(__dirname, 'pacts')],7};8importData(opts).then(() => {9 console.log('Success');10 process.exit(0);11}).catch((e) => {12 console.log('Error: ', e);13 process.exit(1);14});15I can see that you are running the pact-node importData method with the pact broker url, a consumer version of “1.0.0”, and consumer version tags of “prod” and “test”. I can also see that you are running the pact-node import

Full Screen

Using AI Code Generation

copy

Full Screen

1var pact = require('pact-foundation-pact-node');2var opts = {3};4pact.publishPacts(opts)5 .then(function () {6 console.log('Pact contract publishing complete!')7 console.log('')8 console.log('=> Username: dXfltyFMgNOFZAxr8io9wJ37iUpY42M')9 console.log('=> Password: O5AIZWxelWbLvqMd8PkAVycBJh2Psyg1')10 console.log('to see your contracts.')11 })12 .catch(function (e) {13 console.log('Pact contract publishing failed: ', e)14 })15{16 "provider": {17 },18 "consumer": {19 },20 {21 "request": {22 },23 "response": {24 "headers": {25 "Content-Type": "application/json; charset=utf-8"26 },27 {28 }29 }30 }31 "metadata": {32 "pact-specification": {33 },34 "pact-jvm": {35 }36 }37}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { importData } = require('pact-js');2const { importData } = require('pact-js');3const { importData } = require('pact-js');4const { importData } = require('pact-js');5const { importData } = require('pact-js');6const { importData } = require('pact-js');7const { importData } = require('pact-js');8const { importData } = require('pact-js');

Full Screen

Using AI Code Generation

copy

Full Screen

1const {Pact} = require('@pact-foundation/pact');2const {importData} = Pact;3const data = importData('./data.json');4console.log(data);5{6 {7 }8}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { importData } = require('pact-foundation/pact');2const data = importData('./test1.json');3console.log(data);4const { exportData } = require('pact-foundation/pact');5const data = {6 { "name": "Ford", "models": ["Fiesta", "Focus", "Mustang"] },7 { "name": "BMW", "models": ["320", "X3", "X5"] },8 { "name": "Fiat", "models": ["500", "Panda"] }9};10exportData(data, './test1.json');11const { importData } = require('pact-foundation/pact');12const data = importData('./test1.json');13console.log(data);14const { exportData } = require('pact-foundation/pact');15const data = {16 { "name": "Ford", "models": ["Fiesta", "Focus", "Mustang"] },17 { "name": "BMW", "models": ["320", "X3", "X5"] },18 { "name": "Fiat", "models": ["500", "Panda"] }19};20exportData(data, './test1.json');21const { importData } = require('pact-foundation/pact');22const data = importData('./test1.json');23console.log(data);

Full Screen

Using AI Code Generation

copy

Full Screen

1import {importData} from 'pact-foundation-pact-node';2import {deletePact} from 'pact-foundation-pact-node';3import {deletePacts} from 'pact-foundation-pact-node';4import {deleteConsumer} from 'pact-foundation-pact-node';5import {deleteConsumers} from 'pact-foundation-pact-node';6import {deleteProvider} from 'pact-foundation-pact-node';

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Pact } = require('@pact-foundation/pact');2const { Matchers } = require('@pact-foundation/pact/dsl/matchers');3const { getMovies } = require('./client');4const { somethingLike: like } = Matchers;5describe('Pact with Movies API', () => {6 const provider = new Pact({7 });8 beforeAll(() => provider.setup());9 afterAll(() => provider.finalize());10 describe('when a request to list movies is made', () => {11 beforeAll(() => {12 return provider.addInteraction({13 withRequest: {14 headers: {15 }16 },17 willRespondWith: {18 headers: {19 'Content-Type': 'application/json;charset=utf-8'20 },21 body: {22 movies: like(['movie1', 'movie2'])23 }24 }25 });26 });27 afterAll(() => provider.finalize());28 test('returns a successful body', () => {29 return getMovies(url, provider.mockService.port).then(response => {30 expect(response.status).toEqual(200);31 expect(response.data).toEqual({ movies: ['movie1', 'movie2'] });32 });33 });34 });35});36const axios = require('axios');37const getMovies = (url, port) => {38 return axios.get(`${url}:${port}/movies`);39};40module.exports = {

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pact-foundation-pact automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful