How to use queryOrMutation method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

dataStore.js

Source:dataStore.js Github

copy

Full Screen

1//@flow2import { normalize } from "normalizr-gre";3import URL from "url";4import Mutation from "./Mutation";5import Query from "./Query";6import ConnectionQuery from "./ConnectionQuery";7import type { Connection } from "./ConnectionQuery";8import { merge } from "./ImmutableUtils";9import isEqual from "lodash/isEqual";10import type RestlayProvider from "./RestlayProvider";11export const DATA_FETCHED = "@@restlay/DATA_FETCHED";12export const DATA_FETCHED_FAIL = "@@restlay/DATA_FETCHED_FAIL";13const DATA_CONNECTION_SPLICE = "@@restlay/DATA_CONNECTION_SPLICE";14export type Entities = {15 [_: string]: { [_: string]: Object }16};17type Result<R> = {18 result: R,19 time: number20};21export type Store = {22 entities: Entities,23 results: { [_: string]: Result<any> }24};25type DispatchF = (action: Object) => void;26type GetState = () => { data: Store };27export function getPendingQueryResult<R>(28 store: Store,29 query: Query<any, R> | ConnectionQuery<any, any>30): ?Result<R> {31 return store.results[query.getCacheKey()];32}33export function queryCacheIsFresh(store: Store, query: Query<*, *>): boolean {34 const cache = getPendingQueryResult(store, query);35 if (!cache) return false;36 return Date.now() < cache.time + 1000 * query.cacheMaxAge;37}38const initialState: Store = {39 entities: {},40 results: {}41};42// NB we do not preserve the entities object immutable, but only for the object entity itself43function mergeEntities(prev: Entities, patch: Entities): Entities {44 const all = { ...patch, ...prev }; // potentially there are new collections45 const entities = {};46 for (let type in all) {47 const patchColl = patch[type];48 const oldColl = all[type];49 entities[type] = merge(oldColl, patchColl, isEqual);50 }51 return entities;52}53const emptyConnection: Connection<any> = {54 edges: [],55 pageInfo: { hasNextPage: true }56};57const accumulateConnectionEdges = <T>(58 oldConnection: ?Connection<T>,59 connection: Connection<T>60): Connection<T> => {61 if (!oldConnection) return connection;62 const pageInfo = { ...connection.pageInfo };63 if (connection.pageInfo.hasNextPage && connection.edges.length === 0) {64 console.warn(65 "API issue: connection says hasNextPage but edges.length is 0!"66 );67 pageInfo.hasNextPage = false;68 }69 const edges = oldConnection.edges.concat(connection.edges);70 if (process.env.NODE_ENV === "development" && oldConnection) {71 const cursors = {};72 edges.forEach((e, i) => {73 if (!e.cursor) {74 console.warn("API issue: an edge must have a cursor defined");75 }76 if (cursors[e.cursor]) {77 console.warn(78 "API issue: duplicate cursor found at index " + i + ": " + e.cursor79 );80 }81 cursors[e.cursor] = true;82 });83 }84 return {85 edges,86 pageInfo87 };88};89const sliceConnection = <T>(90 connection: Connection<T>,91 length: number92): Connection<T> => ({93 pageInfo: { hasNextPage: true },94 edges: connection.edges.slice(0, length)95});96// TODO we need to split into more functions:97// one for mutation98// one for query99// one for connection query (or more functions, initial query / more page ?)100export const executeQueryOrMutation =101 // network is dynamically provided so the library can be mocked (e.g. for tests)102 (ctx: RestlayProvider) => <Out>(103 queryOrMutation:104 | Query<any, Out>105 | Mutation<any, Out>106 | ConnectionQuery<any, any>107 ) => (dispatch: DispatchF, getState: GetState) => {108 let uri = queryOrMutation.uri;109 let cacheKey, method, body;110 // TODO ConnectionQuery don't stick very well in the normal Query paradigm111 // and later we might really split into 2 different parts112 if (queryOrMutation instanceof ConnectionQuery) {113 const store = getState();114 const cache = getPendingQueryResult(store.data, queryOrMutation);115 const size = queryOrMutation.getSize();116 const shouldReset = !queryOrMutation.firstQueryDone;117 // FIXME this is a hack! need a better refactoring of all of these118 const count =119 cache && !shouldReset120 ? cache.result.pageInfo.hasNextPage121 ? size - cache.result.edges.length122 : 0123 : size;124 if (count < 0) {125 const cacheKey = queryOrMutation.getCacheKey();126 //$FlowFixMe127 return Promise.resolve().then(() => {128 // needs to happen in async129 dispatch({130 type: DATA_CONNECTION_SPLICE,131 cacheKey,132 size,133 queryOrMutation134 });135 return cache ? sliceConnection(cache.result, size) : emptyConnection;136 });137 } else if (count === 0) {138 // $FlowFixMe139 return Promise.resolve((cache && cache.result) || emptyConnection);140 } else {141 const params = queryOrMutation.getPaginationURLParams(142 count,143 shouldReset || !cache || cache.result.edges.length === 0144 ? undefined145 : cache.result.edges[cache.result.edges.length - 1].cursor146 );147 const { pathname, query } = URL.parse(uri, true);148 uri = URL.format({149 pathname,150 query: { ...query, ...params }151 });152 }153 }154 if (queryOrMutation instanceof Mutation) {155 method = queryOrMutation.method;156 body = queryOrMutation.getBody();157 } else {158 cacheKey = queryOrMutation.getCacheKey();159 const pendingPromise = ctx.getPendingQuery(queryOrMutation);160 if (pendingPromise) return pendingPromise;161 method = "GET";162 }163 const promise = ctx164 .network(uri, method, body)165 .then(data => {166 const result = normalize(167 data,168 queryOrMutation.getResponseSchema() || {}169 );170 let resetConnection = false;171 if (172 queryOrMutation instanceof Query ||173 queryOrMutation instanceof ConnectionQuery174 ) {175 ctx.removePendingQuery(queryOrMutation);176 }177 if (queryOrMutation instanceof ConnectionQuery) {178 resetConnection = !queryOrMutation.firstQueryDone;179 queryOrMutation.firstQueryDone = true;180 }181 dispatch({182 type: DATA_FETCHED,183 result,184 queryOrMutation,185 cacheKey,186 resetConnection187 });188 return data;189 })190 .catch(error => {191 if (192 queryOrMutation instanceof Query ||193 queryOrMutation instanceof ConnectionQuery194 ) {195 ctx.removePendingQuery(queryOrMutation);196 }197 dispatch({198 type: DATA_FETCHED_FAIL,199 error,200 queryOrMutation,201 cacheKey202 });203 throw error;204 });205 if (206 queryOrMutation instanceof Query ||207 queryOrMutation instanceof ConnectionQuery208 ) {209 ctx.setPendingQuery(queryOrMutation, promise);210 }211 return promise;212 };213const reducers = {214 [DATA_CONNECTION_SPLICE]: (store, { size, cacheKey }) => {215 if (!cacheKey) {216 return store;217 } else {218 return {219 ...store,220 results: {221 ...store.results,222 [cacheKey]: {223 result: sliceConnection(store.results[cacheKey].result, size),224 time: Date.now()225 }226 }227 };228 }229 },230 [DATA_FETCHED]: (231 store,232 { queryOrMutation, result, cacheKey, resetConnection }233 ) => {234 const entities = mergeEntities(store.entities, result.entities);235 if (!cacheKey) {236 return { ...store, entities };237 } else {238 return {239 entities,240 results: {241 ...store.results,242 [cacheKey]: {243 result:244 queryOrMutation instanceof ConnectionQuery && !resetConnection245 ? accumulateConnectionEdges(246 // FIXME this is always appending, there is no way to reset this..247 // actually will need to differenciate the initial FETCH from PAGINATE248 // also there will be some obvious DEV checks to do, like there is not supposed to be dups in cursors ...249 store.results[cacheKey] && store.results[cacheKey].result,250 result.result251 )252 : result.result,253 time: Date.now()254 }255 }256 };257 }258 }259};260export const reducer = (state: * = initialState, action: Object) => {261 if (action.type in reducers) {262 const patch = reducers[action.type](state, action);263 if (patch) {264 return { ...state, ...patch };265 }266 }267 return state;...

Full Screen

Full Screen

index.ts

Source:index.ts Github

copy

Full Screen

1import 'isomorphic-fetch'2import { polyfill } from 'es6-promise'3polyfill()4interface RequestOptions {5 method: string6 headers: any7 body: string8}9/**10 * @param {string} url - Your GraphQL Endpoint11 */12class graphQlClient {13 private url: string14 private options: any = {}15 constructor (url: string) {16 this.url = url17 }18 /**19 * @param {object} options20 */21 public setOptions(options: any) {22 this.options = options23 }24 /**25 * @param {string} queryOrMutation - A valid GraphQL query or mutation (subscriptions not supported!)26 * @param {object} variables - GraphQL variables27 */28 public execute<R = any, V = any>(queryOrMutation: string, variables?: V) {29 const { url } = this30 return new Promise<R>((resolve, reject) => {31 if (url && url.length > 0) {32 if (validateUrl(url)) {33 if (queryOrMutation) {34 let graphql = JSON.stringify({35 query: queryOrMutation36 })37 38 if (variables) {39 graphql = JSON.stringify({40 query: queryOrMutation,41 variables: variables42 })43 }44 45 let requestOptions: RequestOptions = {46 method: 'POST',47 headers: {48 'Content-Type': 'application/json'49 },50 body: graphql,51 ...this.options52 }53 54 fetch(url, requestOptions)55 .then(response => {56 return response.json()57 })58 .then(result => {59 if (result.errors) {60 reject(result)61 } else {62 resolve(result.data)63 }64 })65 .catch(error => reject(error))66 } else {67 reject('Please provide a Query or Mutation!')68 }69 } else {70 reject('Invalid URL!')71 }72 } else {73 reject('Please provide a GraphQL endpoint (e.g: https://localhost:3000/graphql/)')74 }75 })76 }77}78const validateUrl = (Url: string) => {79 const validationRegEx = /[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/ig80 return validationRegEx.test(Url)81}82const gql = (literals: TemplateStringsArray, ...placeholders: any) => {83 return literals.reduce((prev, curr, index) => prev + curr + placeholders[index])84}85export {86 gql87}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...8 url: "ws://localhost:4000/graphql",9 lazy: false,10});11// query, mutation12async function queryOrMutation(subscribePayload) {13 return new Promise((resolve, reject) => {14 let result;15 const cleanUp = client.subscribe(subscribePayload, {16 next: (data) => (result = data),17 complete: () => {18 cleanUp();19 return resolve(result);20 },21 error: reject,22 });23 });24}25// subscription26function useSubscription(operationPayload, callback) {27 const callbackRef = useRef(callback);28 callbackRef.current = callback;29 useEffect(() => {30 const subscription = client.subscribe(operationPayload, {31 next: (result) => {32 callbackRef.current(result);33 },34 error: (errors) => {35 callbackRef.current({ errors });36 },37 complete: () => {38 subscription.unsubscribe();39 },40 });41 return () => {42 subscription.unsubscribe();43 };44 }, []); // eslint-disable-line45 // the effect should be run when component is mounted and unmounted46}47const queryFn = async ({ queryKey }) => {48 const [query, variables, operationName, extensions] = queryKey;49 const { data } = await queryOrMutation({50 query,51 variables,52 operationName,53 extensions,54 });55 return data;56};57const queryClient = new QueryClient({58 defaultOptions: {59 queries: {60 // default function used by all useQuery calls61 queryFn,62 // prevents re-fetching queries by default, data is updated manually with subscriptions63 staleTime: Infinity,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { queryOrMutation } from "pact-foundation-pact-web";2 query {3 allUsers {4 }5 }6`;7queryOrMutation(url, query).then((data) => {8 console.log(data);9});10describe("test2", () => {11 it("should return all users", () => {12 cy.readFile("pacts/my_consumer-my_provider.json").then((pact) => {13 const interaction = pact.interactions[0];14 cy.intercept(interaction.request.method, interaction.request.path, {15 }).as("graphql");16 cy.get("button").click();17 cy.wait("@graphql").its("response.statusCode").should("eq", 200);18 });19 });20});

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