Best JavaScript code snippet using pact-foundation-pact
user.js
Source:user.js
1import { editIncomeQuery, addIncomeQuery, deleteIncomeQuery } from '@/graphQL/incomeQuery'2import { editExpenseQuery, addExpenseQuery, deleteExpenseQuery } from '@/graphQL/expenseQuery'3import { addTransactionQuery, editTransactionQuery, deleteTransactionQuery } from '@/graphQL/transactionsQuery'4import axios from 'axios'5import Vue from 'vue'6const state = {7 goal: null,8 // balance: 0,9 wallets: [],10 incomes: [],11 expenses: [],12 monthlyReports: [],13 walletTypeList: [14 {15 value: 'Debit card',16 i18: 'debitCard'17 }, {18 value: 'Credit card',19 i18: 'creditCard'20 },21 {22 value: 'Cash',23 i18: 'cash'24 }25 ]26}27const getters = {28 user: state => {29 return state30 },31 userBalance: state => {32 let balance = 033 state.wallets.forEach(wallet => {34 if (wallet.walletType === 'Debit card' || wallet.walletType === 'Cash') {35 balance += wallet.amount36 }37 if (wallet.walletType === 'Credit card') {38 balance -= wallet.amount39 }40 })41 return balance42 },43 userTransactions: state => {44 // console.log('user vuex tra', getters.usersIncomesAndExpenses())45 const transactions = []46 state.monthlyReports.forEach(report => {47 report.transactions.forEach(transaction => {48 transactions.push(transaction)49 })50 })51 const sortedTransactions = transactions.sort(function (a, b) {52 return new Date(a.date) - new Date(b.date)53 })54 return sortedTransactions55 },56 currentPeriodReport: state => {57 let currentReport = {}58 const d = new Date()59 const currentPeriod = `${d.getMonth() + 1}-${d.getFullYear()}`60 state.monthlyReports.find((report, index) => {61 if (report.period === currentPeriod) {62 currentReport = state.monthlyReports[index]63 return true64 }65 })66 return currentReport67 },68 upcoming: state => {69 const datedTransactions = [...state.incomes]70 state.expenses.forEach(expense => {71 if (expense.expenseType === 'Fixed') {72 datedTransactions.push(expense)73 }74 })75 if (datedTransactions.length < 1) {76 return false77 }78 datedTransactions.sort((a, b) => (79 new Date(a.nextPayout) > new Date(b.nextPayout) ? -1 : 180 ))81 const result = {82 type: datedTransactions[0].category === 'Income' ? 'income' : 'expense',83 category: datedTransactions[0].category,84 subcategory: datedTransactions[0].subcategory,85 date: new Date(datedTransactions[0].nextPayout),86 value: datedTransactions[0].amount87 }88 return result89 },90 creditBalance: state => {91 const credits = ['Visa', 'MasterCard']92 let creditBalance = 093 state.wallets.forEach(wallet => {94 if (credits.includes(wallet.walletType)) {95 creditBalance += wallet.amount96 }97 })98 return creditBalance99 }100}101const mutations = {102 setUserData (state, data) {103 state.wallets = data.wallets104 state.incomes = data.incomes105 state.expenses = data.expenses106 state.goal = data.goal107 state.monthlyReports = data.monthlyReports108 },109 clearUserData (state) {110 state.goal = null111 state.balance = 0112 state.wallets = []113 state.incomes = []114 state.expenses = []115 state.monthlyReports = []116 },117 addUserItem (state, data) {118 const userItemType = data.type119 const userItem = { ...data }120 delete userItem.type121 state[userItemType] = [...state[userItemType], userItem]122 },123 editUserItem (state, data) {124 const userItemType = data.type125 const userItem = { ...data }126 let itemIndex127 state[userItemType].find((item, index) => {128 if (item._id === data._id) {129 itemIndex = index130 }131 })132 delete userItem.type133 Vue.set(state[userItemType], itemIndex, userItem)134 // state[userItemType][itemIndex] = data135 },136 deleteUserItem (state, data) {137 state[data.userItemType] = state[data.userItemType].filter(i => i._id !== data._id)138 },139 addGoal (state, goal) {140 state.goal = goal141 },142 addTransaction (state, user) {143 state.wallets = user.wallets144 state.incomes = user.incomes145 state.expenses = user.expenses146 state.monthlyReports = user.monthlyReports147 },148 deleteTransaction (state, user) {149 state.wallets = user.wallets150 state.incomes = user.incomes151 state.expenses = user.expenses152 state.monthlyReports = user.monthlyReports153 }154}155const actions = {156 addIncome: async function ({ commit }, income) {157 const graphqlQuery = addIncomeQuery(income)158 try {159 const response = await axios.post('/', graphqlQuery)160 const resData = response.data.data.addIncome161 resData.type = 'incomes'162 resData.nextPayout = new Date(resData.nextPayout)163 commit('addUserItem', resData)164 return true165 } catch (err) {166 // console.log(err.response)167 return false168 }169 },170 editIncome: async function ({ commit }, income) {171 const graphqlQuery = editIncomeQuery(income)172 try {173 const response = await axios.post('', graphqlQuery)174 const resData = response.data.data.editIncome175 resData.nextPayout = new Date(resData.nextPayout)176 resData.type = 'incomes'177 commit('editUserItem', resData)178 return true179 } catch (err) {180 // console.log(err.response)181 return false182 }183 },184 deleteIncome: async function ({ commit }, expenseId) {185 const graphqlQuery = deleteIncomeQuery(expenseId)186 try {187 const response = await axios.post('', graphqlQuery)188 const resData = response.data.data.deleteIncome189 if (resData === 'success') {190 const data = {191 userItemType: 'incomes',192 _id: expenseId193 }194 commit('deleteUserItem', data)195 }196 } catch (err) {197 // console.log(err.response)198 return false199 }200 },201 addExpense: async function ({ commit }, expense) {202 const graphqlQuery = addExpenseQuery(expense)203 try {204 const response = await axios.post('', graphqlQuery)205 const resData = response.data.data.addExpense206 resData.type = 'expenses'207 commit('addUserItem', resData)208 return true209 } catch (err) {210 // console.log(err.response)211 commit('addError', err.response.data.errors[0].message)212 return false213 }214 },215 editExpense: async function ({ commit }, expense) {216 const graphqlQuery = editExpenseQuery(expense)217 try {218 const response = await axios.post('', graphqlQuery)219 const resData = response.data.data.editExpense220 resData.type = 'expenses'221 commit('editUserItem', resData)222 return true223 } catch (err) {224 // console.log(err.response)225 return false226 }227 },228 deleteExpense: async function ({ commit }, expenseId) {229 const graphqlQuery = deleteExpenseQuery(expenseId)230 try {231 const response = await axios.post('', graphqlQuery)232 const resData = response.data.data.deleteExpense233 if (resData.success === 'true') {234 const data = {235 userItemType: 'expenses',236 _id: resData.deletedId237 }238 commit('deleteUserItem', data)239 }240 } catch (err) {241 // console.log(err.response)242 return false243 }244 },245 addTransaction: async function ({ commit }, transaction) {246 const graphqlQuery = addTransactionQuery(transaction)247 try {248 const response = await axios.post('', graphqlQuery)249 const resData = response.data.data.addTransaction250 commit('addTransaction', resData)251 return true252 } catch (err) {253 // console.log(err.response)254 return false255 }256 },257 editTransaction: async function ({ commit }, transaction) {258 const graphqlQuery = editTransactionQuery(transaction)259 try {260 const response = await axios.post('', graphqlQuery)261 const resData = response.data.data.editTransaction262 commit('addTransaction', resData)263 return true264 } catch (err) {265 // console.log('error editing transaction', err.response)266 return false267 }268 },269 deleteTransaction: async function ({ commit }, transactionId) {270 const graphqlQuery = deleteTransactionQuery(transactionId)271 try {272 const response = await axios.post('', graphqlQuery)273 const resData = response.data.data.deleteTransaction274 commit('deleteTransaction', resData)275 return true276 } catch (err) {277 // console.log(err.response)278 return false279 }280 }281}282export default {283 state,284 getters,285 mutations,286 actions...
graphql-bigcommerce.js
Source:graphql-bigcommerce.js
1const productFragment = `2fragment ProductFields on Product {3 id4 entityId5 name6 sku7 path8 description9 addToCartUrl10 addToWishlistUrl11 categories {12 edges {13 node {name}14 }15 }16 defaultImage {17 img320px: url(width: 320)18 img640px: url(width: 640)19 img960px: url(width: 960)20 img1280px: url(width: 1280)21 altText22 }23 prices {24 price {25 value26 currencyCode27 }28 }29}30`31const categoryFragment = `32fragment CategoryFields on CategoryTreeItem {33 name34 path35 entityId36 description37 productCount38}39`40async function sendQuery(query) {41 const url = new URL(process.env.storeUrl)42 const graphQLUrl = `${url.origin}/graphql`43 // Fetch data from the GraphQL Storefront API44 return await fetch(graphQLUrl, {45 method: 'POST',46 // mode: 'cors',47 headers: {48 'Content-Type': 'application/json',49 Authorization: `Bearer ${process.env.BIGCOMMERCE_TOKEN}`,50 },51 body: JSON.stringify({52 query,53 }),54 })55 .then((res) => res.json())56 .then((res) => res.data)57}58export async function getStoreSettings() {59 const graphQLQuery = `60 query SettingsQuery {61 site {62 settings {63 storeHash64 storeName65 }66 }67 }68 `69 return await sendQuery(graphQLQuery)70}71export async function getCategories() {72 const graphQLQuery = `73 query CategoryQuery {74 site {75 categoryTree {76 ...CategoryFields77 children {78 ...CategoryFields79 children {80 ...CategoryFields81 }82 }83 }84 }85 }86 ${categoryFragment}87 `88 return await sendQuery(graphQLQuery)89}90export async function categoriesByIds(ids) {91 const query = `92 query CategoryTree3LevelsDeep {93 site {94 categoryTree {95 ...CategoryFields96 children {97 ...CategoryFields98 children {99 ...CategoryFields100 }101 }102 }103 }104 }105 ${categoryFragment}`106 const response = await sendQuery(query)107 const categories = response.site.categoryTree.filter((c) =>108 ids.includes(c.entityId)109 )110 return categories111}112export async function getCategoryPath(id) {113 const query = `114 query CategoryTree3LevelsDeep {115 site {116 categoryTree {117 ...CategoryFields118 children {119 ...CategoryFields120 children {121 ...CategoryFields122 }123 }124 }125 }126 }127 ${categoryFragment}`128 try {129 const response = await sendQuery(query)130 const categories = response.site.categoryTree131 const categoryPath = categories.filter((c) => c.entityId === id)132 return categoryPath ? categoryPath[0].path : false133 } catch (e) {134 console.error(e)135 }136}137export async function getProductCount() {138 const graphQLQuery = `139 query ProductCount {140 site {141 categoryTree {142 ... on CategoryTreeItem {143 name144 productCount145 }146 }147 }148 }149 `150 return await sendQuery(graphQLQuery)151}152export async function getProducts({153 perPage = 50,154 cursor,155 direction = 'after',156}) {157 let cursorString = ''158 let dir = 'first'159 if (cursor && cursor.length) {160 cursorString = `, ${direction}: "${cursor}"`161 if (direction === 'before') dir = 'last'162 }163 const graphQLQuery = `164 query AllProducts {165 site {166 products(${dir}: ${perPage}${cursorString}) {167 pageInfo {168 startCursor169 endCursor170 }171 edges {172 node {173 ...ProductFields174 }175 }176 }177 }178 }179 ${productFragment}180 `181 return await sendQuery(graphQLQuery)182}183export async function getProductsById({184 perPage = 50,185 cursor,186 direction = 'after',187 ids,188}) {189 let cursorString = ''190 let dir = 'first'191 const stringIds = ids ? ids.join(',') : ''192 if (cursor && cursor.length) {193 if (direction === 'before') dir = 'last'194 cursorString = `, ${direction}: "${cursor}"`195 }196 const graphQLQuery = `197 query ProductsById {198 site {199 products(entityIds: [${stringIds}], ${dir}: ${perPage}${cursorString}) {200 pageInfo {201 startCursor202 endCursor203 }204 edges {205 node {206 ...ProductFields207 }208 }209 }210 }211 }212 ${productFragment}213 `214 return await sendQuery(graphQLQuery)215}216export async function getProductById(productId) {217 const graphQLQuery = `218 query ProductId {219 site {220 product${productId ? `(entityId:${productId})` : ''} {221 ...ProductFields222 }223 }224 }225 ${productFragment}`226 // Fetch data from the GraphQL Storefront API227 return await sendQuery(graphQLQuery)228}229export async function getProductBySlug(slug) {230 const graphQLQuery = `231 query ProductSlug {232 site {233 route${slug ? `(path:"${slug}")` : ''} {234 node {235 id236 ...ProductFields237 }238 }239 }240 }241 ${productFragment}`242 // Fetch data from the GraphQL Storefront API243 return await sendQuery(graphQLQuery)244}245export async function getProductsByPath(path) {246 const correctPath =247 path.startsWith('/') && path.endsWith('/') ? path : `/${path}/`248 const graphQLQuery = `249 query ProductPath {250 site {251 route${path ? `(path:"${correctPath}")` : ''} {252 node {253 ... on Category {254 name255 path256 products {257 edges {258 node {259 ...ProductFields260 }261 }262 }263 }264 }265 }266 }267 }268 ${productFragment}269 `270 return await sendQuery(graphQLQuery)271}272export async function getProductsByCategory(id) {273 const categoryPath = await getCategoryPath(id)274 // Fetch data from the GraphQL Storefront API275 return getProductsByPath(categoryPath)...
graphql-query-builder.js
Source:graphql-query-builder.js
1/**2* GraphQL query builder library3*/4let gql5 (function(gql) {6 const GraphQlQuery = /** @class */ (function() {7 function GraphQlQuery(fnName, argumentsMap) {8 let _a9 if (argumentsMap === void 0) {10 argumentsMap = {};11 }12 this.head = typeof fnName === 'string' ? {13 fnName: (_a = {}, _a[fnName] = fnName, _a)14 } : {15 fnName: fnName16 };17 this.head.argumentsMap = argumentsMap18 this.body = []19 this.isContainer = false20 this.isWithoutBody = false21 }22 GraphQlQuery.prototype.select = function() {23 const selects = []24 for (var _i = 0; _i < arguments.length; _i++) {25 selects[_i] = arguments[_i];26 }27 if (this.isContainer) {28 throw new Error('Can`t use selection on joined query.');29 }30 this.body = this.body.concat(selects.map(function(item) {31 let _a32 let selection = {}33 if (typeof item === 'string') {34 selection.attr = (_a = {}, _a[item] = item, _a);35 selection.argumentsMap = {};36 } else if (item instanceof GraphQlQuery) {37 selection = item;38 } else if (typeof item === 'object') {39 selection.argumentsMap = item['_filter'] || {};40 delete item['_filter'];41 selection.attr = item;42 }43 return selection;44 }));45 return this;46 };47 GraphQlQuery.prototype.filter = function(argumentsMap) {48 for (let key in argumentsMap) {49 if (argumentsMap.hasOwnProperty(key)) {50 this.head.argumentsMap[key] = argumentsMap[key];51 }52 }53 return this;54 };55 GraphQlQuery.prototype.join = function() {56 const queries = [];57 for (let _i = 0; _i < arguments.length; _i++) {58 queries[_i] = arguments[_i];59 }60 const combined = new GraphQlQuery('');61 combined.isContainer = true;62 combined.body.push(this);63 combined.body = combined.body.concat(queries);64 return combined;65 };66 GraphQlQuery.prototype.withoutBody = function() {67 if (this.isContainer) {68 throw new Error('Can`t use withoutBody on joined query.');69 }70 this.isWithoutBody = true;71 return this;72 };73 GraphQlQuery.prototype.toString = function() {74 if (this.isContainer) {75 return "{ " + this.buildBody() + " }";76 } else if (this.isWithoutBody) {77 return "{ " + this.buildHeader() + " }";78 } else {79 return "{ " + this.buildHeader() + "{" + this.buildBody() +80 "} }";81 }82 };83 GraphQlQuery.prototype.buildHeader = function() {84 return this.buildAlias(this.head.fnName) + this.buildArguments(85 this.head.argumentsMap);86 };87 GraphQlQuery.prototype.buildArguments = function(argumentsMap) {88 const query = this.objectToString(argumentsMap);89 return query ? "(" + query + ")" : '';90 };91 GraphQlQuery.prototype.getGraphQLValue = function(value) {92 const _this = this;93 if (Array.isArray(value)) {94 var arrayString = value.map(function(item) {95 return _this.getGraphQLValue(item);96 }).join();97 return "[" + arrayString + "]";98 } else if (value instanceof EnumValue) {99 return value.toString();100 } else if ("object" === typeof value) {101 return '{' + this.objectToString(value) + '}';102 } else {103 return JSON.stringify(value);104 }105 };106 GraphQlQuery.prototype.objectToString = function(obj) {107 const _this = this;108 return Object.keys(obj).map(function(key) {109 return key + ": " + _this.getGraphQLValue(obj[key]);110 }).join(', ');111 };112 GraphQlQuery.prototype.buildAlias = function(attr) {113 const alias = Object.keys(attr)[0];114 let value = this.prepareAsInnerQuery(attr[alias]);115 value = (alias !== value) ? alias + ": " + value : value;116 return value;117 };118 GraphQlQuery.prototype.buildBody = function() {119 const _this = this;120 return this.body.map(function(item) {121 if (item instanceof GraphQlQuery) {122 return _this.prepareAsInnerQuery(item);123 } else {124 return _this.buildAlias(item['attr']) + _this.buildArguments(125 item['argumentsMap']);126 }127 }).join(' ');128 };129 GraphQlQuery.prototype.prepareAsInnerQuery = function(query) {130 let ret = '';131 if (query instanceof GraphQlQuery) {132 ret = query.toString();133 ret = ret.substr(2, ret.length - 4);134 } else {135 ret = query.toString();136 }137 return ret;138 };139 return GraphQlQuery;140 }());141 gql.GraphQlQuery = GraphQlQuery;142 const EnumValue = /** @class */ (function() {143 function EnumValue(value) {144 this.value = value;145 }146 EnumValue.prototype.toString = function() {147 return this.value;148 };149 return EnumValue;150 }());151 gql.EnumValue = EnumValue;152 function enumValue(value) {153 return new EnumValue(value);154 }155 gql.enumValue = enumValue;156})(gql || (gql = {}));157if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {158 module.exports = {159 GraphQlQuery: gql.GraphQlQuery,160 EnumValue: gql.EnumValue,161 enumValue: gql.enumValue162 };...
Using AI Code Generation
1var pact = require('pact-foundation/pact-node');2var path = require('path');3var opts = {4 pactUrls: [path.resolve(process.cwd(), 'pacts', 'test1-test2.json')],5};6pact.verifyPacts(opts).then(function (output) {7 console.log('Pact Verification Complete!')8 console.log(output)9}).catch(function (e) {10 console.log('Pact Verification Failed: ', e)11});12var pact = require('pact-foundation/pact-node');13var path = require('path');14var opts = {15 pactUrls: [path.resolve(process.cwd(), 'pacts', 'test2-test1.json')],16};17pact.verifyPacts(opts).then(function (output) {18 console.log('Pact Verification Complete!')19 console.log(output)20}).catch(function (e) {21 console.log('Pact Verification Failed: ', e)22});
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!!