function PrimusRelayNetwork (primus, opts) {
  var primusRelayClient = new PrimusRelayClient(primus, opts)
  return Relay.Network.create(
    primusRelayClient.fetch,
    primusRelayClient.subscribe
  )
}
Beispiel #2
0
export function createResolver(fetcher) {
  const environment = new Environment({
    network: Network.create((...args) => fetcher.fetch(...args)),
    store: new Store(new RecordSource()),
  });

  return new Resolver(environment);
}
function createResolver(fetcher) {
  const environment = new _relayRuntime.Environment({
    network: _relayRuntime.Network.create((...args) => fetcher.fetch(...args)),
    store: new _relayRuntime.Store(new _relayRuntime.RecordSource()) });


  return new _foundRelay.Resolver(environment);
}
const createRelayEnvironment = (token: ?string, records: Object = {}) => {
  const store = new Store(new RecordSource(records));
  const network = Network.create((operation, variables) =>
    // eslint-disable-next-line no-undef
    fetch(GRAPHQL_ENDPOINT, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        ...(token != null ? { authorization: `Bearer ${token}` } : null),
      },
      body: JSON.stringify({
        query: operation.text,
        variables,
      }),
    }).then(response => response.json()),
  );
  return new Environment({ store, network });
};
Beispiel #5
0
  const response = await fetch('/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: operation.text,
      variables,
    }),
  });

  return response.json();
}

const modernEnvironment: Environment = new Environment({
  network: Network.create(fetchQuery),
  store: new Store(new RecordSource()),
});

const rootElement = document.getElementById('root');

if (rootElement) {
  ReactDOM.render(
    <QueryRenderer
      environment={modernEnvironment}
      query={graphql`
        query appQuery($userId: String) {
          user(id: $userId) {
            ...TodoApp_user
          }
        }
Beispiel #6
0
 const network = Network.create((operation, variables) => {
   const global = getGlobal();
   if (global.token === null) {
     var optext = operation.text.replace(/\n/g, "");
     return fetch(`${GRAPHQL_ENDPOINT_OPEN}?query=${encodeURIComponent(optext)}`, {
       method: 'GET',
       headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json'
       }
     }).then(response => {
       return response.json();
     })
   } else {
     console.log(JSON.stringify({
       query: operation.text,
       variables,
     }));
     return fetch(`${GRAPHQL_ENDPOINT_AUTH}`, {
       method: 'POST',
       headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json',
         'Authorization': `Bearer ${global.token}`
       },
       body: JSON.stringify({
         query: operation.text,
         variables,
       }),
     }).then(response => {
       return response.json()
     })
   }
 })
Beispiel #7
0
export default function createEnvironment(props){
	let {user, token, appId, supportOffline, network, showMessage, loading, isDev}=props

	if(supportOffline){
		supportOffline.user=user
	}

	function handleErrors(errors){
		let {message,stack}=errors.reduce((state,a)=>{
			state.message.add(a.message)
			state.stack.add(a.stack)
			return state
		}, {message:new Set(), stack:new Set()})
		if(isDev){
			showMessage({message:Array.from(message).join("|"),level:"error"})
			console.error("Server Error\r\n"+Array.from(stack).join("\r\n"))
		}else{
			showMessage({message:Array.from(message).join("|"),level:"warn"})
		}
	}


	function fetcherOnline(opt){
		if(supportOffline)
			supportOffline.setSource(source)

		const {service,optics:report}=props
		return fetch(service,{
			method: 'POST',
			...opt,
			headers: {
				'content-type': 'application/json',
				"X-Application-ID": appId,
				"X-Session-Token": token,
				...(opt?opt.headers:null)
			},
		})
		.then(res=>{
			if(!res.ok){
				throw new Error(res.statusText)
			}
			return res.json()
		})
		.then(res=>{
			if(res.errors)
				handleErrors(res.errors, showMessage)

			if(res.extensions)
				report(res.extensions.report)

			return res
		})
	}

	function fetchQueryOnline(operation, variables, cacheConfig,uploadables){
		return fetcherOnline({
			body: JSON.stringify({
				query: isDev===true ? operation.text : undefined, // GraphQL text from input
				id: isDev===true ? undefined : operation.name,
				variables,
			}),
		})
		.catch(e=>{

			network("offline")

			if(supportOffline)
				return fetchQueryOffline(operation, variables, cacheConfig,uploadables)

			throw e
		})
	}

	function fetchQueryOffline(operation, variables, cacheConfig,uploadables){
		supportOffline.unsetSource(source)
		return supportOffline.runQL(operation.text, variables)
			.then(res=>{
				if(res.errors)
					handleErrors(res.errors, showMessage)

				if(isDev){
					console.dir({
						query:operation.text,
						variables,
						result:res
					})
				}
				return res
			})
	}

	function fetchQuery(){
		return (()=>{
			loading(true)
			if(network()=="online")
				return fetchQueryOnline(...arguments)
			else if(supportOffline)
				return fetchQueryOffline(...arguments)
			else
				return Promise.resolve(NoService)
		})().catch(e=>{
			loading(false)
			showMessage({message:e.message, level:"error"})
			console.debug({error:e, props, network:network()})
			throw e
		}).then(res=>{
			loading(false)
			return res
		})
	}


	return Object.assign(new Environment({
		handlerProvider,
		network:Network.create(fetchQuery),
		store,
	}),{
		changeToken(newToken){
			token=newToken
		},
		fetcher(req){
			loading(true)
			return (()=>{
				if(network()=="online"){
					return fetcherOnline(...arguments)
				}else if(supportOffline){
					let {query, variables}=JSON.parse(req.body)
					return supportOffline.runQL(query, variables)
						.then(result=>{
							if(isDev){
								console.dir({
									query,
									variables,
									result
								})
							}
							return result
						})
				}else{
					return Promise.resolve(NoService)
				}
			})().catch(e=>{
				loading(false)
				showMessage({message:e.message, level:"error"})
				return e
			}).then(res=>{
				loading(false)
				return res
			})
		},
		runQL(query, variables){
			loading(true)
			return (()=>{
				if(network()=="online"){
					return fetcherOnline({body:JSON.stringify(query)})
				}else if(supportOffline){
					return supportOffline.runQL(query, variables)
						.then(result=>{
							if(isDev){
								console.dir({
									query,
									variables,
									result
								})
							}
							return result
						})
				}else {
					return Promise.resolve(NoService)
				}
			})().catch(e=>{
				loading(false)
				showMessage({message:e.message, level:"error"})
				return e
			}).then(res=>{
				loading(false)
				return res
			})
		}
	});
}
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem(GC_AUTH_TOKEN)}`
        },
        body: JSON.stringify({
            query: operation.text,
            variables
        }),
    }).then(response => {
        return response.json()
    })
}

const setupSubscription = (config, variables, cacheConfig, observer) => {
    const query = config.text
    
    const subscriptionClient = new SubscriptionClient('wss://subscriptions.graph.cool/v1/cj8br66e107j10144q85i39lx', {reconnect: true})
    subscriptionClient.subscribe({query, variables}, (error, result) => {
        observer.onNext({data: result})
    })
}

// for querying the server - instantiated with a function that returns a promise
const network = Network.create(fetchQuery, setupSubscription)

// instantiating the Relay environment
const environment = new Environment({
    network,
    store
})

export default environment