Best JavaScript code snippet using pact-foundation-pact
api.js
Source:api.js
...31// The API is different in two ways: we never want undo enabled, and32// we also need to notify the UI manually if stuff has changed (if33// they are connecting to an already running instance, the UI should34// update). The wrapper handles that.35function withMutation(handler) {36 return args => {37 return runMutator(38 async () => {39 let latestTimestamp = getClock().timestamp.toString();40 let result = await handler(args);41 let rows = await db.all(42 'SELECT DISTINCT dataset FROM messages_crdt WHERE timestamp > ?',43 [latestTimestamp]44 );45 // Only send the sync event if anybody else is connected46 if (connection.getNumClients() > 1) {47 connection.send('sync-event', {48 type: 'success',49 tables: rows.map(row => row.dataset)50 });51 }52 return result;53 },54 { undoDisabled: true }55 );56 };57}58let handlers = {};59async function validateMonth(month) {60 if (!month.match(/^\d{4}-\d{2}$/)) {61 throw APIError('Invalid month format, use YYYY-MM: ' + month);62 }63 if (!IMPORT_MODE) {64 let { start, end } = await handlers['get-budget-bounds']();65 let range = monthUtils.range(start, end);66 if (!range.includes(month)) {67 throw APIError('No budget exists for month: ' + month);68 }69 }70}71async function validateExpenseCategory(debug, id) {72 if (id == null) {73 throw APIError(`${debug}: category id is required`);74 }75 let row = await db.first('SELECT is_income FROM categories WHERE id = ?', [76 id77 ]);78 if (!row) {79 throw APIError(`${debug}: category "${id}" does not exist`);80 }81 if (row.is_income !== 0) {82 throw APIError(`${debug}: category "${id}" is not an expense category`);83 }84}85let batchPromise = null;86handlers['api/batch-budget-start'] = async function() {87 if (batchPromise) {88 throw APIError('Cannot start a batch process: batch already started');89 }90 // If we are importing, all we need to do is start a raw database91 // transaction. Updating spreadsheet cells doesn't go through the92 // syncing layer in that case.93 if (IMPORT_MODE) {94 db.asyncTransaction(() => {95 return new Promise((resolve, reject) => {96 batchPromise = { resolve, reject };97 });98 });99 } else {100 batchMessages(() => {101 return new Promise((resolve, reject) => {102 batchPromise = { resolve, reject };103 });104 });105 }106};107handlers['api/batch-budget-end'] = async function() {108 if (!batchPromise) {109 throw APIError('Cannot end a batch process: no batch started');110 }111 batchPromise.resolve();112 batchPromise = null;113};114handlers['api/load-budget'] = async function({ id }) {115 let { id: currentId } = prefs.getPrefs() || {};116 if (currentId !== id) {117 connection.send('start-load');118 let { error } = await handlers['load-budget']({ id });119 if (!error) {120 connection.send('finish-load');121 } else {122 connection.send('show-budgets');123 if (error === 'out-of-sync-migrations' || error === 'out-of-sync-data') {124 throw new Error(125 'This budget cannot be loaded with this version of the app.'126 );127 } else if (error === 'budget-not-found') {128 throw new Error(129 'Budget "' +130 id +131 '" not found. Check the id of your budget in the "Advanced" section of the settings page.'132 );133 } else {134 throw new Error('We had an unknown problem opening "' + id + '".');135 }136 }137 }138};139handlers['api/start-import'] = async function({ budgetName }) {140 // Notify UI to close budget141 await handlers['close-budget']();142 // Create the budget143 await handlers['create-budget']({ budgetName, avoidUpload: true });144 // Clear out the default expense categories145 await db.runQuery('DELETE FROM categories WHERE is_income = 0');146 await db.runQuery('DELETE FROM category_groups WHERE is_income = 0');147 // Turn syncing off148 setSyncingMode('import');149 connection.send('start-import');150 IMPORT_MODE = true;151};152handlers['api/finish-import'] = async function() {153 sheet.get().markCacheDirty();154 // We always need to fully reload the app. Importing doesn't touch155 // the spreadsheet, but we can't just recreate the spreadsheet156 // either; there is other internal state that isn't created157 let { id } = prefs.getPrefs();158 await handlers['close-budget']();159 await handlers['load-budget']({ id });160 await handlers['get-budget-bounds']();161 await sheet.waitOnSpreadsheet();162 await cloudStorage.upload().catch(err => {});163 connection.send('finish-import');164 IMPORT_MODE = false;165};166handlers['api/abort-import'] = async function() {167 if (IMPORT_MODE) {168 let { id } = prefs.getPrefs();169 await handlers['close-budget']();170 await handlers['delete-budget']({ id });171 connection.send('show-budgets');172 }173 IMPORT_MODE = false;174};175handlers['api/query'] = async function({ query }) {176 return aqlQuery(query);177};178handlers['api/budget-months'] = async function() {179 let { start, end } = await handlers['get-budget-bounds']();180 return monthUtils.range(start, end);181};182handlers['api/budget-month'] = async function({ month }) {183 await validateMonth(month);184 let groups = await db.getCategoriesGrouped();185 let sheetName = monthUtils.sheetForMonth(month);186 function value(name) {187 let v = sheet.get().getCellValue(sheetName, name);188 return v === '' ? 0 : v;189 }190 // This is duplicated from main.js because the return format is191 // different (for now)192 return {193 month,194 incomeAvailable: value('available-funds'),195 lastMonthOverspent: value('last-month-overspent'),196 forNextMonth: value('buffered'),197 totalBudgeted: value('total-budgeted'),198 toBudget: value('to-budget'),199 fromLastMonth: value('from-last-month'),200 totalIncome: value('total-income'),201 totalSpent: value('total-spent'),202 totalBalance: value('total-leftover'),203 categoryGroups: groups.map(group => {204 if (group.is_income) {205 return {206 ...categoryGroupModel.toExternal(group),207 received: value('total-income'),208 categories: group.categories.map(cat => ({209 ...categoryModel.toExternal(cat),210 received: value(`sum-amount-${cat.id}`)211 }))212 };213 }214 return {215 ...categoryGroupModel.toExternal(group),216 budgeted: value(`group-budget-${group.id}`),217 spent: value(`group-sum-amount-${group.id}`),218 balance: value(`group-leftover-${group.id}`),219 categories: group.categories.map(cat => ({220 ...categoryModel.toExternal(cat),221 budgeted: value(`budget-${cat.id}`),222 spent: value(`sum-amount-${cat.id}`),223 balance: value(`leftover-${cat.id}`),224 carryover: value(`carryover-${cat.id}`)225 }))226 };227 })228 };229};230handlers['api/budget-set-amount'] = withMutation(async function({231 month,232 categoryId,233 amount234}) {235 return handlers['budget/budget-amount']({236 month,237 category: categoryId,238 amount239 });240});241handlers['api/budget-set-carryover'] = withMutation(async function({242 month,243 categoryId,244 flag245}) {246 await validateMonth(month);247 await validateExpenseCategory('budget-set-carryover', categoryId);248 return handlers['budget/set-carryover']({249 startMonth: month,250 category: categoryId,251 flag252 });253});254handlers['api/transactions-export'] = async function({255 transactions,256 categoryGroups,257 payees258}) {259 return handlers['transactions-export']({260 transactions,261 categoryGroups,262 payees263 });264};265handlers['api/transactions-import'] = withMutation(async function({266 accountId,267 transactions268}) {269 return handlers['transactions-import']({ accountId, transactions });270});271handlers['api/transactions-add'] = withMutation(async function({272 accountId,273 transactions274}) {275 await addTransactions(accountId, transactions, { runTransfers: false });276 return 'ok';277});278handlers['api/transactions-get'] = async function({279 accountId,280 startDate,281 endDate282}) {283 let { data } = await aqlQuery(284 q('transactions')285 .filter({286 $and: [287 accountId && { account: accountId },288 startDate && { date: { $gte: startDate } },289 endDate && { date: { $lte: endDate } }290 ].filter(Boolean)291 })292 .select('*')293 .options({ splits: 'grouped' })294 );295 return data;296};297handlers['api/transactions-filter'] = async function({ text, accountId }) {298 throw new Error('`filterTransactions` is deprecated, use `runQuery` instead');299};300handlers['api/transaction-update'] = withMutation(async function({301 id,302 fields303}) {304 let { data } = await aqlQuery(305 q('transactions')306 .filter({ id })307 .select('*')308 .options({ splits: 'grouped' })309 );310 let transactions = ungroupTransactions(data);311 if (transactions.length === 0) {312 return [];313 }314 let { diff } = updateTransaction(transactions, fields);315 return handlers['transactions-batch-update'](diff);316});317handlers['api/transaction-delete'] = withMutation(async function({ id }) {318 let { data } = await aqlQuery(319 q('transactions')320 .filter({ id })321 .select('*')322 .options({ splits: 'grouped' })323 );324 let transactions = ungroupTransactions(data);325 if (transactions.length === 0) {326 return [];327 }328 let { diff } = deleteTransaction(transactions, id);329 return handlers['transactions-batch-update'](diff);330});331handlers['api/accounts-get'] = async function() {332 let accounts = await db.getAccounts();333 return accounts.map(account => accountModel.toExternal(account));334};335handlers['api/account-create'] = withMutation(async function({336 account,337 initialBalance = null338}) {339 return handlers['account-create']({340 name: account.name,341 type: account.type,342 offBudget: account.offbudget,343 closed: account.closed,344 // Current the API expects an amount but it really should expect345 // an integer346 balance: initialBalance != null ? integerToAmount(initialBalance) : null347 });348});349handlers['api/account-update'] = withMutation(async function({ id, fields }) {350 return db.updateAccount({ id, ...accountModel.fromExternal(fields) });351});352handlers['api/account-close'] = withMutation(async function({353 id,354 transferAccountId,355 transferCategoryId356}) {357 return handlers['account-close']({358 id,359 transferAccountId,360 categoryId: transferCategoryId361 });362});363handlers['api/account-reopen'] = withMutation(async function({ id }) {364 return handlers['account-reopen']({ id });365});366handlers['api/account-delete'] = withMutation(async function({ id }) {367 return handlers['account-close']({ id, forced: true });368});369handlers['api/categories-get'] = async function({ grouped } = {}) {370 let result = await handlers['get-categories']();371 return grouped372 ? result.grouped.map(categoryGroupModel.toExternal)373 : result.list.map(categoryModel.toExternal);374};375handlers['api/category-group-create'] = withMutation(async function({ group }) {376 return handlers['category-group-create']({ name: group.name });377});378handlers['api/category-group-update'] = withMutation(async function({379 id,380 fields381}) {382 return handlers['category-group-update']({383 id,384 ...categoryGroupModel.fromExternal(fields)385 });386});387handlers['api/category-group-delete'] = withMutation(async function({388 id,389 transferCategoryId390}) {391 return handlers['category-group-delete']({392 id,393 transferId: transferCategoryId394 });395});396handlers['api/category-create'] = withMutation(async function({ category }) {397 return handlers['category-create']({398 name: category.name,399 groupId: category.group_id,400 isIncome: category.is_income401 });402});403handlers['api/category-update'] = withMutation(async function({ id, fields }) {404 return handlers['category-update']({405 id,406 ...categoryModel.fromExternal(fields)407 });408});409handlers['api/category-delete'] = withMutation(async function({410 id,411 transferCategoryId412}) {413 return handlers['category-delete']({414 id,415 transferId: transferCategoryId416 });417});418handlers['api/payees-get'] = async function() {419 let payees = await handlers['payees-get']();420 return payees.map(payeeModel.toExternal);421};422handlers['api/payee-create'] = withMutation(async function({ payee }) {423 return handlers['payee-create']({ name: payee.name });424});425handlers['api/payee-update'] = withMutation(async function({ id, fields }) {426 return handlers['payees-batch-change']({427 updated: [{ id, ...payeeModel.fromExternal(fields) }]428 });429});430handlers['api/payee-delete'] = withMutation(async function({ id }) {431 return handlers['payees-batch-change']({ deleted: [{ id }] });432});433handlers['api/payee-rules-get'] = async function({ payeeId }) {434 let rules = await handlers['payees-get-rules']({ id: payeeId });435 return rules.map(payeeRuleModel.toExternal);436};437handlers['api/payee-rule-create'] = withMutation(async function({438 payee_id,439 rule440}) {441 return handlers['payees-add-rule']({442 payee_id,443 type: rule.type,444 value: rule.value || null445 });446});447handlers['api/payee-rule-update'] = withMutation(async function({448 id,449 fields450}) {451 return handlers['payees-update-rule']({452 id,453 ...payeeRuleModel.fromExternal(fields)454 });455});456handlers['api/payee-rule-delete'] = withMutation(async function({ id }) {457 return handlers['payees-delete-rule']({ id });458});459export default function(serverHandlers) {460 handlers = Object.assign({}, serverHandlers, handlers);461 return handlers;...
SubmitComments.js
Source:SubmitComments.js
...48const options = {49 name: 'comments',50 args: { name: 'String', comment: 'String' }51};...
withMutation.js
Source:withMutation.js
1import React, { Component } from "react";2import { curryRight } from "lodash";3import { Mutation } from "react-apollo";4import MaskWithBackground from "../Mask/MaskWithBackground";5const withMutation = curryRight(6 (WrappedComponent, mutation, mutationProps = {}) => {7 class WithMutation extends Component {8 render = () => (9 <Mutation {...mutationProps} mutation={mutation}>10 {(mutate, { loading, error, data }) => {11 if (loading) {12 return <MaskWithBackground messageKey="loading" />;13 } else if (error) {14 return <MaskWithBackground messageKey="error" color="error" />;15 }16 return (17 <WrappedComponent18 {...this.props}19 mutate={mutate}20 mutateResult={data}21 />22 );23 }}24 </Mutation>25 );26 }27 WithMutation.displayName = `WithMutation(${WrappedComponent.displayName})`;28 return WithMutation;29 },30 331);...
Using AI Code Generation
1const { Matchers, Pact } = require('@pact-foundation/pact');2const { like, term, somethingLike, eachLike, eachLike } = Matchers;3const { get } = require('axios');4const pact = new Pact({5});6describe('Pact', () => {7 describe('Test Provider', () => {8 beforeAll(() => {9 return pact.setup();10 });11 afterAll(() => {12 return pact.finalize();13 });14 it('should validate the expectations of Test Consumer', () => {15 return pact.verify();16 });17 it('should return a valid response', () => {18 const expectedResponse = {19 };20 const expectedRequest = {21 };22 return pact.addInteraction({23 willRespondWith: {24 headers: {25 },26 }27 })28 .then(() => {29 })30 .then((response) => {31 expect(response.status).toEqual(200);32 expect(response.data).toEqual(expectedResponse);33 });34 });35 });36});37{38 "scripts": {39 },
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!!