Skip to content

Commit

Permalink
Merge pull request #34 from mmeigs/master
Browse files Browse the repository at this point in the history
Null Problem and Hunt and Gather
  • Loading branch information
travismfrank committed Sep 19, 2020
2 parents 517425b + b85f700 commit 32da0a3
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 68 deletions.
13 changes: 7 additions & 6 deletions ObsidianWrapper/ObsidianWrapper.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function ObsidianWrapper(props) {
const [cache, setCache] = React.useState({});

// Primary function, provides access to fetching and caching capabilities
async function fetcher(query, options = {}) {
async function gather(query, options = {}) {
// Desctructuring of optional parameters, default values are defined and may be over written
const {
endpoint = '/graphql',
Expand Down Expand Up @@ -49,9 +49,10 @@ function ObsidianWrapper(props) {
console.log('--------------');
return new Promise((resolve, reject) => resolve(checkStorage));
}
/* ^^^ COMMENT OUT THESE LINES FOR SERVER CACHE ^^^ */
}
// If not found in cache, query is excecuted
/* COMMENT OUT THESE LINES FOR SERVER CACHE */

// Conditional check, if poll interval has been defined
if (pollInterval) {
console.log(
Expand All @@ -63,14 +64,14 @@ function ObsidianWrapper(props) {
setInterval(() => {
console.log('--------------');
console.log('Fetching query with poll interval');
fetchData(query, endpoint, destructure, sessionStore);
hunt(query, endpoint, destructure, sessionStore);
}, pollInterval);
}
console.log('--------------');
console.log('Fetching Data');
// Excection of fetch
return new Promise((resolve, reject) =>
resolve(fetchData(query, endpoint, destructure, sessionStore))
resolve(hunt(query, endpoint, destructure, sessionStore))
);
}
// Function to update the global cache with new response data
Expand All @@ -89,7 +90,7 @@ function ObsidianWrapper(props) {
}

// Excecutes graphql fetch request
async function fetchData(query, endpoint, destructure, sessionStore) {
async function hunt(query, endpoint, destructure, sessionStore) {
try {
const respJSON = await fetch(endpoint, {
method: 'POST',
Expand Down Expand Up @@ -131,7 +132,7 @@ function ObsidianWrapper(props) {

// Returning Provider React component that allows consuming components to subscribe to context changes
return (
<cacheContext.Provider value={{ cache, fetcher, clearCache }} {...props} />
<cacheContext.Provider value={{ cache, gather, hunt, clearCache }} {...props} />
);
}
// Declaration of custom hook to allow access to provider
Expand Down
4 changes: 2 additions & 2 deletions demo/Components/Book.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ declare global {
}

const Book = (props: any) => {
const { fetcher } = useObsidian();
const { gather } = useObsidian();

return (
<div className='book-list' style={cardStyle}>
Expand All @@ -25,7 +25,7 @@ const Book = (props: any) => {

<button
onClick={() => {
fetcher(
gather(
` query { getBook(id: ${props.id}) { id title author description publicationDate publisher coverPrice whereToBuy {
id
name
Expand Down
6 changes: 3 additions & 3 deletions demo/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,17 @@ const App = () => {
const [info, setInfo] = (React as any).useState({});
const [books, setBooks] = (React as any).useState([]);
const [page, setPage] = (React as any).useState(1);
const { fetcher } = useObsidian();
const { gather } = useObsidian();


(React as any).useEffect(() => {
fetcher(`{ getEightBooks(id: 1) { id title author } }`).then((resp: any) =>
gather(`{ getEightBooks(id: 1) { id title author } }`).then((resp: any) =>
setBooks([...resp.data.getEightBooks])
);
}, []);

const pageTurn = (id: any) => {
fetcher(` query{ getEightBooks(id: ${id}) { id title author } } `).then(
gather(` query{ getEightBooks(id: ${id}) { id title author } } `).then(
(resp: any) => {
setBooks([...resp.data.getEightBooks]);
let curPage = id;
Expand Down
20 changes: 0 additions & 20 deletions package.json

This file was deleted.

5 changes: 3 additions & 2 deletions src/destructureQueries.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ async function buildResultsObject(hashes, obsidianSchema, queryObj, cache) {
id
}
}

// Prevent overriding of id //
if (property.toLowerCase() === 'id' || property.toLowerCase() === '_id') continue;

Expand All @@ -64,8 +65,8 @@ async function buildResultsObject(hashes, obsidianSchema, queryObj, cache) {
propVal = JSON.parse(await retrieveScalar(hashes[j], cache));
} else {
propVal = await retrieveScalar(hashes[j], cache);
if (propVal.slice(1, 5) === 'null') propVal = null;
}
if (propVal && propVal.slice(1, 5) === 'null') propVal = null;
}
queryResult[id][property] = propVal;
// If this field is complex, recursive call to build nested property object //
} else {
Expand Down
3 changes: 2 additions & 1 deletion src/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ async function hashAndStoreFieldsOfObject(typeSchemaName, fields, obsidianTypeSc
if (newId) {
value[nestedSchemaName + '~' + newId] = true;
} else {
value = null;
value[`${nestedSchemaName}~null`] = true;
}
}
// NamedType
Expand Down Expand Up @@ -124,6 +124,7 @@ async function hashAndStoreFieldsOfObject(typeSchemaName, fields, obsidianTypeSc
}

function hashGenerator(typeSchemaName, id, property) {
if (!id) return typeSchemaName + '~null~' + property;
return typeSchemaName + '~' + String(id) + '~' + property;
}

Expand Down
66 changes: 32 additions & 34 deletions src/obsidian.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export interface ObsidianRouterOptions<T> {
resolvers: ResolversProps;
context?: (ctx: any) => any;
usePlayground?: boolean;
useCache?: boolean;
}

export interface ResolversProps {
Expand All @@ -37,6 +38,7 @@ export async function ObsidianRouter<T>({
resolvers,
context,
usePlayground = true,
useCache = true,
}: ObsidianRouterOptions<T>): Promise<T> {
const router = new Router();

Expand All @@ -59,44 +61,40 @@ export async function ObsidianRouter<T>({
console.log('Incoming Query:');
console.log(body.query);

if (useCache) {
// Send query off to be destructured and found in Redis if possible //
const obsidianReturn = await destructureQueries(body.query, obsidianSchema);

console.log('Obsidian Reconstructed Result:', obsidianReturn)
/* COMMENT OUT THESE LINES FOR WRAPPER CACHE */
if (obsidianReturn) {
response.status = 200;
response.body = obsidianReturn;

console.log('Reconstructed results object using cache, returning without querying db.')

return;
} else {
/* COMMENT OUT THESE LINES FOR WRAPPER CACHE */
const result = await (graphql as any)(
schema,
body.query,
resolvers,
contextResult,
body.variables || undefined,
body.operationName || undefined
);

response.status = 200;
response.body = result;

// Store the new results
console.log('GraphQL result object');
console.log(result);
console.log('Sending results off to normalize...')
/* COMMENT OUT THESE LINES FOR WRAPPER CACHE */
normalizeResult(body.query, result, obsidianSchema);
/* COMMENT OUT THESE LINES FOR WRAPPER CACHE */

return;
/* COMMENT OUT THESE LINES FOR WRAPPER CACHE */

if (obsidianReturn) {
response.status = 200;
response.body = obsidianReturn;

console.log('Reconstructed results object using cache, returning without querying db.')

return;
}
}
/* COMMENT OUT THESE LINES FOR WRAPPER CACHE */
const result = await (graphql as any)(
schema,
body.query,
resolvers,
contextResult,
body.variables || undefined,
body.operationName || undefined
);

response.status = 200;
response.body = result;

// Store the new results
console.log('GraphQL result object');
console.log(result);
console.log('Sending results off to normalize...')

if (useCache) normalizeResult(body.query, result, obsidianSchema);

return;
} catch (error) {
response.status = 200;
console.log('error message', error.message);
Expand Down

0 comments on commit 32da0a3

Please sign in to comment.