@@ -386,7 +386,7 @@ Here is how you can use the queries and mutations generated for your data, using
386386
387387## Usage with Node
388388
389- Install the module locally
389+ Install the module locally:
390390
391391``` sh
392392npm install --save-dev json-graphql-server
@@ -407,6 +407,80 @@ app.use('/graphql', jsonGraphqlExpress(data));
407407app .listen (PORT );
408408```
409409
410+ ## Usage on client
411+
412+ Install the module locally:
413+
414+ ``` sh
415+ npm install --save json-graphql-server
416+ ```
417+
418+ Then use the ` graphQLClientServer ` function:
419+
420+ ``` js
421+ import { graphQLClientServer } from ' json-graphql-server' ;
422+
423+ const data = [... ];
424+
425+ const server = GraphQLClientServer ({
426+ data,
427+ url: ' http://localhost:3000/graphql'
428+ });
429+
430+ server .start ();
431+ ```
432+
433+ This will intercepts all XMLHttpRequests and make them responds like a GraphQL server when the url matches the one specified.
434+
435+ For example:
436+
437+ ``` js
438+ window .document
439+ .getElementById (' btnLoadPosts' )
440+ .addEventListener (' click' , function () {
441+ var xhr = new XMLHttpRequest ();
442+ xhr .responseType = ' json' ;
443+ xhr .open (" POST" , " http://localhost:3000/graphql" , true );
444+ xhr .setRequestHeader (" Content-Type" , " application/json" );
445+ xhr .setRequestHeader (" Accept" , " application/json" );
446+ xhr .onerror = function (error ) {
447+ console .error (error);
448+ }
449+ xhr .onload = function () {
450+ const result = JSON .parse (xhr .responseText );
451+ console .log (' data returned:' , result);
452+ alert (' Found ' + result .data .allPosts .length + ' posts' );
453+ }
454+ const body = JSON .stringify ({ query: ' query allPosts { allPosts { id } }' });
455+ xhr .send (body);
456+ });
457+ ```
458+
459+ ## Usage in browser through script
460+
461+ Add a ` script ` tag referencing the library:
462+
463+ ``` html
464+ <script src =" ../lib/json-graphql-server.min.js" ></script >
465+ ```
466+
467+ It will expose the ` GraphQLClientServer ` as a global object:
468+
469+ ``` html
470+ <script type =" text/javascript" >
471+ window .addEventListener (' load' , function () {
472+ const data = [... ];
473+
474+ const server = GraphQLClientServer ({
475+ data,
476+ url: ' http://localhost:3000/graphql'
477+ });
478+
479+ server .start ();
480+ });
481+ </script >
482+ ```
483+
410484## Adding Authentication, Custom Routes, etc.
411485
412486` json-graphql-server ` doesn't deal with authentication or custom routes. But you can use your favorite middleware with Express:
0 commit comments