Skip to content

Commit

Permalink
pseudo code query method
Browse files Browse the repository at this point in the history
  • Loading branch information
mattkrick committed Feb 23, 2016
0 parents commit 317b392
Show file tree
Hide file tree
Showing 29 changed files with 3,266 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["es2015", "stage-0"],
}
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
lib
*.log
node_modules
.idea
4 changes: 4 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
src/
__tests__/
node_modules
.idea
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Matt Krick

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
136 changes: 136 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
[![npm version](https://badge.fury.io/js/cashay.svg)](https://badge.fury.io/js/cashay)
#cashay
relay for the rest of us

WIP. Be a pal. Make a PR.

##Installation
`npm i -S cashay`

##Setup

Just like relay, the goal is to get the benefits of graphql while minimizing client payload.
To do so, we'll make a script that writes the GraphQL schema to a JSON file.
Since this is specific to your project, you'll need to write this yourself.
For example, I put the clientSchema in my `build` folder.
I also need to drain my database connection pool that is filled when the `rootSchema` is accessed.
So, my file looks like this:

```javascript
// updateSchema.js
require('babel-register');
require('babel-polyfill');

const path = require('path');
const rootSchema = require('../src/server/graphql/rootSchema');
const graphql = require('graphql').graphql;
const introspectionQuery = require('graphql/utilities').introspectionQuery;
const r = require('../src/server/database/rethinkdriver');

(async () => {
const result = await graphql(rootSchema, introspectionQuery);
if (result.errors) {
console.log(result.errors)
} else {
fs.writeFileSync(path.join(__dirname, '../build/clientSchema.json'), JSON.stringify(result, null, 2));
}
r.getPool().drain();
})();
```
I recommend writing an npm script and executing it whenever your GraphQL schema changes.
If you want to get fancy, you can put a watcher on your GraphQL folder to run it on file change.

Next, we'll need to make a babel plugin. Don't worry, cashay already has a babel plugin factory. All you need to do is inject the schema you just made:

```javascript
// cashayPlugin.js
const createPlugin = require('cashay/lib/babel-plugin');
const schema = require('../build/schema.json');
module.exports = createPlugin(schema);
```

Now, we need to include that plugin in our `.babelrc`:

```javascript
{
"plugins": [
["./cashayPlugin.js"]
]
}
```
Success! Now Babel will statically analyze all of our queries and give each one a bespoke schema.
This means our client bundle stays tiny.

##Usage

Cashay provides 3 useful items:

```javascript
import {CashayQL, Cashay, cashayReducer} from 'cashay';
```

Prefixing all your query strings with `CashayQL` tells Babel to do its magic. For example:

```javascript
const queryString = CashayQL`
query {
getComments {
id
body
}
}`
```

`Cashay` is a class that takes a redux store and transport (AKA fetcher function).

```javascript
const cashay = new Cashay({store: myReduxStore, transport: graphQLFetcher});
```

Your transport should call your GraphQL endpoint and return an object with a `data` and `error` prop.
If you call multiple GraphQL servers, you'll need multiple transports.

```javascript
export const fetchGraphQL = async graphParams => {
const authToken = localStorage.getItem('myToken');
const res = await fetch('http://localhost:3000/graphql', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify(graphParams)
});
const {data, errors} = await res.json();
return {data, error: getPrettyErrors(errors)}
}
```

`cashayReducer` is as easy; just add it to your `combineReducers`.


##API

```javascript
cashay.query(queryString, options)
```

Calling `query` will fetch your queryString from the graphQL server and put it in your redux store.
Currently, it's very naive.
It doesn't reduce the query.
It doesn't know if there are pending fetches.
It doesn't run the reducer in a webworker.

But, you can use it for predictive fetches.
For example, call it when someone hovers their mouse over the "load data" button.
No need to wait for the `Relay.container` to load.

Ha! Take that relay! :smile:.

##Contributing

There is a LOT of work to be done. Join the fun, check out the issues, and make a PR.

##License

MIT
44 changes: 44 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"name": "cashay",
"version": "0.1.0",
"description": "relay for the rest of us",
"main": "lib/index.js",
"scripts": {
"clean": "rimraf lib",
"lint": "xo src/index.js --esnext --space --fix",
"build": "babel --presets es2015,stage-0 -d lib/ src/",
"watch": "babel -w --presets es2015,stage-0 -d lib/ src/",
"prepublish": "npm run clean && npm run build",
"test": "ava ./src/**/__tests__/**/*-test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mattkrick/cashay.git"
},
"keywords": [
"relay",
"client",
"cache",
"redux"
],
"author": "Matt Krick <[email protected]>",
"license": "MIT",
"bugs": {
"url": "https://github.com/mattkrick/cashay/issues"
},
"homepage": "https://github.com/mattkrick/cashay#readme",
"devDependencies": {
"ava": "^0.11.0",
"babel-cli": "^6.4.5",
"babel-preset-es2015": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"babel-register": "^6.4.3",
"graphql": "^0.4.17",
"normalizr": "^2.0.0",
"rimraf": "^2.5.1",
"xo": "^0.12.1"
},
"dependencies": {
"immutable": "^3.7.6"
}
}
98 changes: 98 additions & 0 deletions src/Cashay.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {FETCH_DATA_REQUEST, FETCH_DATA_SUCCESS, FETCH_DATA_ERROR} from './duck';
import {normalize} from 'normalizr';
import {parse} from 'graphql/language/parser';

export default class Cashay {
constructor({store, transport, schema}) {
this._store = store;
this._transport = transport;
this._schema = schema;
}

async query(queryString, options = {}) {
//const {string, schema} = queryString;
const {variables, clientSchema, forceFetch, paginationWords, idFieldName} = options;
const {dispatch} = this._store;
const cahsayDataStore = this._store.getState().getIn(['cashay', 'data']);
const queryAST = parse(queryString, {noLocation: true, noSource: true});
// based on query name + args, does it exist in cashay.denomralizedResults
const denormLocationInCashayState = getDenormLocationFromQueryAST(queryAST, clientSchema, variables);
const existsInStore = isDenormLocationInStore(this._store, denormLocationInCashayState);
// if yes && !forceFetch, return
if (existsInStore && !forceFetch) return;
// denormalize queryAST from store data and create dependencies, return minimziedAST
const context = buildExecutionContext(clientSchema, queryAST, {variables, paginationWords, idFieldName, store: this._store})
const {dependencies, denormalizedResult, minimizedAST} = denormalizeAndCreateDependencies(queryAST, context);
// insert denomralized JSON object in state.cashay.denormalizedResults
dispatch({
type: '@@cashay/INSERT_DENORMALIZED',
payload: {
dependencies,
location: denormLocationInCashayState,
result: denormalizedResult
}
})
//if not complete,
if (minimizedAST) {
// print (minimizedAST)
const minimizedQuerySTring = print(minimizedAST);
// send minimizedQueryString to server and await minimizedQueryResponse
const minimizedQueryResponse = await this._transport(minimizedQuerySTring, variables)
// normalize response
const context = buildExecutionContext(clientSchema, queryAST, {variables, paginationWords, idFieldName})
const normalizedMinimizedQueryResponse = normalize(minimizedQueryResponse, context)
// stick normalize data in store
dispatch({
type: '@@cashay/INSERT_NORMALIZED',
payload: {
response: normalizedMinimizedQueryResponse
}
})
// denormalize queryAST from store data and create dependencies
const {dependencies, denormalizedResult, minimizedAST} = denormalizeAndCreateDependencies(queryAST, this._store);
dispatch({
type: '@@cashay/INSERT_DENORMALIZED',
payload: {
dependencies,
location: denormLocationInCashayState,
result: denormalizedResult
}
})

}


//const partial = denormalize(cahsayDataStore.toJS(), varSchema, queryAST)
// see what data we have in the store
//const schemaKeys = Object.keys(schema);
//schemaKeys.forEach(key => {
// if (schema[key].constructor.name === 'EntitySchema') {
// console.log('checking key', key)
// const entityId = cahsayDataState.getIn(['result', key]);
// console.log('entId', entityId, cahsayDataState)
// if (entityId) {
// const subStateName = schema[key].getKey();
// const obj = cahsayDataState.getIn(['entities', subStateName, entityId]);
// console.log('CACHED RES', obj);
// }
// }
//})

//dispatch({type: FETCH_DATA_REQUEST});
//const {error, data} = await this._transport({query: string});
//if (error) {
// return dispatch({
// type: FETCH_DATA_ERROR,
// error
// })
//}
//console.log('RESP', data)
//const payload = normalize(data, schema);
////const ans = denormalize(payload, schema);
//dispatch({
// type: FETCH_DATA_SUCCESS,
// payload
//});
}
}

21 changes: 21 additions & 0 deletions src/CashayQL.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
///* Code from hueypetersen.com */
//
//import {Schema, arrayOf, unionOf} from 'normalizr';
//
//const CashayQL = (string, ...args) => {
// throw new Error('Cashay: Did you install your Babel plugin?');
//}
//
//Object.assign(CashayQL, {
// schema(key, definition) {
// const schema = new Schema(key);
// if (definition) {
// schema.define(definition);
// }
// return schema;
// },
// arrayOf,
// unionOf
//});
//
//export default CashayQL;
Loading

0 comments on commit 317b392

Please sign in to comment.