Skip to content

Commit

Permalink
Merge pull request #31 from TravisFrankMTG/master
Browse files Browse the repository at this point in the history
Fixed client-side cache to use state
  • Loading branch information
CaliskanBurak authored Sep 18, 2020
2 parents bb7abcc + 3fe2cb4 commit 3b14080
Show file tree
Hide file tree
Showing 7 changed files with 149 additions and 137 deletions.
125 changes: 68 additions & 57 deletions ObsidianWrapper/ObsidianWrapper.jsx
Original file line number Diff line number Diff line change
@@ -1,82 +1,82 @@
import React from 'https://dev.jspm.io/[email protected]';

import clientStorage from './clientStorage.js';

import React from 'https://dev.jspm.io/[email protected]'; // from deps
// import clientStorage from 'https://deno.land/x/[email protected]/ObsidianWrapper/clientStorage.js';
import normalizeResult from '../src/normalize.js';
import destructureQueries from '../src/destructureQueries.js';


// Context will be used to create a custom provider for the application
export const cacheContext = React.createContext();

// Declaration of custom Obsidian Wrapper
function ObsidianWrapper(props) {

const [cache, setCache] = React.useState(clientStorage);

const [cache, setCache] = React.useState({});
// Primary function, provides access to fetching and caching capabilities
async function fetcher(query, options = {}) {
console.log('initial state', window.__INITIAL_STATE__.obsidianSchema)
const obsidianSchema = window.__INITIAL_STATE__.obsidianSchema;
// Desctructuring of optional parameters, default values are defined and may be over written
const { endpoint = '/graphql', pollInterval = null } = options;

/* COMMENT OUT THESE LINES FOR SERVER CACHE */
const obsidianReturn = await destructureQueries(query, obsidianSchema);
// // Conditional to check if query is stored in global cache
if (obsidianReturn) {
console.log('--------------');
console.log('Found it in the cache!!');
console.log('--------------');
// Returning cached response as a promise
return new Promise(
(resolve, reject) => resolve(obsidianReturn)
// This can be uncommeted to store cache in session storage
// resolve(JSON.parse(sessionStorage.getItem(query)))
);
}
// If not found in cache, query is excecuted
else {
console.log(cache);

// Desctructuring of optional parameters, default values are defined and may be over written
const {
endpoint = '/graphql',
pollInterval = null,
destructure = true,
} = options;
if (destructure) {
const obsidianSchema = window.__INITIAL_STATE__.obsidianSchema;
/* COMMENT OUT THESE LINES FOR SERVER CACHE */

// Conditional check, if poll interval has been defined
if (pollInterval) {
console.log(
`Setting ${
pollInterval / 1000
} second poll interval for graphql request`
const deepCache = Object.assign({}, cache);
const obsidianReturn = await destructureQueries(query, obsidianSchema, deepCache);
// // Conditional to check if query is stored in global cache
if (obsidianReturn) {
console.log('--------------');
console.log('Found it in the cache!!');
console.log('--------------');
// Returning cached response as a promise
return new Promise(
(resolve, reject) => resolve(obsidianReturn)
// This can be uncommeted to store cache in session storage
// resolve(JSON.parse(sessionStorage.getItem(query)))
);
// Initiation of reocurring fetch request
setInterval(() => {
console.log('--------------');
console.log('Fetching query with poll interval');
fetchData(query, endpoint);
}, pollInterval);
}
console.log('--------------');
console.log('Fetching Data');
// Excection of fetch
return await fetchData(query, endpoint);
} else {
if (cache[query]) {
console.log('--------------');
console.log('Found it in the cache!!');
console.log('--------------');
return new Promise((resolve, reject) => resolve(cache[query]));
}
}
// 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(
`Setting ${
pollInterval / 1000
} second poll interval for graphql request`
);
// Initiation of reocurring fetch request
setInterval(() => {
console.log('--------------');
console.log('Fetching query with poll interval');
fetchData(query, endpoint);
}, pollInterval);
}
console.log('--------------');
console.log('Fetching Data');
// Excection of fetch
return await fetchData(query, endpoint, destructure);
/* COMMENT OUT THESE LINES FOR SERVER CACHE */
/* COMMENT OUT THESE LINES FOR SERVER CACHE */
}
// Function to update the global cache with new response data
function updateCache(query, response) {
console.log('BEFORE: ', cache);
// Declaring new object with new data to store in cache
const newObj = Object.assign(cache, { [query]: response });
// React hook to update global cache object
setCache(newObj);
console.log('AFTER: ', newObj);
console.log('CACHEEE: ', cache);
// Can be uncommeted to store data in session storage
// sessionStorage.setItem(query, JSON.stringify(response));
}
// Excecutes graphql fetch request
async function fetchData(query, endpoint) {
const obsidianSchema = window.__INITIAL_STATE__.obsidianSchema;
async function fetchData(query, endpoint, destructure) {
try {
const respJSON = await fetch(endpoint, {
method: 'POST',
Expand All @@ -88,11 +88,22 @@ function ObsidianWrapper(props) {
});
const resp = await respJSON.json();
// Excecute function to update the cache with new response

/* COMMENT OUT THESE LINES FOR SERVER CACHE */
normalizeResult(query, resp, obsidianSchema);
/* COMMENT OUT THESE LINES FOR SERVER CACHE */

if (destructure) {
const obsidianSchema = window.__INITIAL_STATE__.obsidianSchema;
/* COMMENT OUT THESE LINES FOR SERVER CACHE */
const deepCache = Object.assign({}, cache);
normalizeResult(query, resp, obsidianSchema, deepCache)
.then(updatedCache => {
for (let key in updatedCache) {
for (let hash in updatedCache[key]) {
updateCache(hash, updatedCache[key][hash]);
}
}
});
/* COMMENT OUT THESE LINES FOR SERVER CACHE */
} else {
updateCache(query, resp);
}
return resp;
} catch (e) {
console.log(e);
Expand Down
1 change: 0 additions & 1 deletion ObsidianWrapper/clientStorage.js

This file was deleted.

3 changes: 1 addition & 2 deletions src/createQueryObj.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export default function(queryName, query, obsidianSchema) {

// Rebuilds and stores parameters //
while (brackets.length === 0) {
console.log('parameter name', parameterName)
if (query[i] === ' ') {
// Skipping everything else for whitespace
} else if (query[i] === '{') {
Expand Down Expand Up @@ -93,4 +92,4 @@ function buildPropertyObject(query, startIdx) {
}
i++;
}
}
}
21 changes: 10 additions & 11 deletions src/dbOps.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import clientStorage from '../ObsidianWrapper/clientStorage.js';

const browser = window.Deno ? false : true;

let redis;
Expand All @@ -13,14 +11,15 @@ if (!browser) {
}


async function checkAndInsert(hash, value, expiration = 20) {
async function checkAndInsert(hash, value, cache, expiration = 20) {
let ifCached;

if (browser) {
ifCached = clientStorage[hash];
ifCached = cache[hash];
if (!ifCached) {
clientStorage[hash] = value;
cache[hash] = value;
}
return cache;
} else {
if (!redis) {
redis = await connectFunc(browser);
Expand Down Expand Up @@ -61,9 +60,9 @@ async function checkAndInsert(hash, value, expiration = 20) {
}
}

async function checkAndRetrieveQuery(hash) {
async function checkAndRetrieveQuery(hash, cache) {
if (browser) {
return clientStorage[hash];
return cache[hash];
} else {
if (!redis) {
redis = await connectFunc(browser);
Expand All @@ -74,9 +73,9 @@ async function checkAndRetrieveQuery(hash) {
}
}

async function retrieveScalar(hash) {
async function retrieveScalar(hash, cache) {
if (browser) {
return clientStorage[hash];
return cache[hash];
} else {
if (!redis) {
redis = await connectFunc(browser);
Expand All @@ -89,9 +88,9 @@ async function retrieveScalar(hash) {
}
}

async function retrieveComplex(hash) {
async function retrieveComplex(hash, cache) {
if (browser) {
return clientStorage[hash];
return cache[hash];
} else {
if (!redis) {
redis = await connectFunc(browser);
Expand Down
26 changes: 12 additions & 14 deletions src/destructureQueries.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import createQueryObj from './createQueryObj.js';
import { findTypeSchemaName, findProp } from './hashOps.js';

// Attempt to rebuild results object if all hashes are found in Redis //
export default async function destructureQueries(query, obsidianSchema) {
export default async function destructureQueries(query, obsidianSchema, cache) {
// Stringify to expose newline characters //
query = JSON.stringify(query)

// Destructure query into array of minified sub-queries //
const queryHashes = await findSpecificQueries(query, obsidianSchema);
const queryHashes = await findSpecificQueries(query, obsidianSchema, cache);

const result = {
data: {}
Expand All @@ -26,15 +26,15 @@ export default async function destructureQueries(query, obsidianSchema) {
const hashes = Object.keys(queryHashes[queryName])

// Attempt to build result object from cache //
result.data[queryName] = await buildResultsObject(hashes, obsidianSchema, queryObj);
result.data[queryName] = await buildResultsObject(hashes, obsidianSchema, queryObj, cache);
};
// If can't reconstruct //
if (Object.keys(result.data).length === 0) return;

return result;
}

async function buildResultsObject(hashes, obsidianSchema, queryObj) {
async function buildResultsObject(hashes, obsidianSchema, queryObj, cache) {
let queryResult = {};

// For each property hash, add to result object //
Expand All @@ -59,11 +59,11 @@ async function buildResultsObject(hashes, obsidianSchema, queryObj) {
const propType = obsidianSchema.obsidianTypeSchema[typeSchemaName][property].type;
let propVal;
if (propType === 'Int' || propType === 'Float') {
propVal = Number(await retrieveScalar(hashes[j]));
propVal = Number(await retrieveScalar(hashes[j], cache));
} else if (propType === 'Boolean') {
propVal = JSON.parse(await retrieveScalar(hashes[j]));
propVal = JSON.parse(await retrieveScalar(hashes[j], cache));
} else {
propVal = await retrieveScalar(hashes[j]);
propVal = await retrieveScalar(hashes[j], cache);
if (propVal.slice(1, 5) === 'null') propVal = null;
}
queryResult[id][property] = propVal;
Expand All @@ -77,12 +77,12 @@ async function buildResultsObject(hashes, obsidianSchema, queryObj) {
queryResult[id][property] = [];
for (let k = 0; k < partialHashesArray.length; k++) {
// Recursive call //
queryResult[id][property].push(await buildResultsObject(batchHash(Object.keys(queryObj.properties[property]), partialHashesArray[k]), obsidianSchema, queryObj));
queryResult[id][property].push(await buildResultsObject(batchHash(Object.keys(queryObj.properties[property]), partialHashesArray[k]), obsidianSchema, queryObj, cache));
}
// Field is NamedType //
} else {
// Recursive call //
queryResult[id][property] = await buildResultsObject(batchHash(Object.keys(queryObj.properties[property]), partialHashes), obsidianSchema, queryObj);
queryResult[id][property] = await buildResultsObject(batchHash(Object.keys(queryObj.properties[property]), partialHashes), obsidianSchema, queryObj, cache);
}
}
}
Expand All @@ -101,7 +101,7 @@ async function buildResultsObject(hashes, obsidianSchema, queryObj) {
}

// Returns obj with minified queries and associated hashes //
async function findSpecificQueries(query, obsidianSchema) {
async function findSpecificQueries(query, obsidianSchema, cache) {
const queryHashes = {};

// Finds first query name //
Expand All @@ -119,16 +119,14 @@ async function findSpecificQueries(query, obsidianSchema) {

// Loop through all sub-queries and find their values in redis
for (let queryHash in queryHashes) {
redisResults[queryHash] = await checkAndRetrieveQuery(queryHashes[queryHash]);
redisResults[queryHash] = await checkAndRetrieveQuery(queryHashes[queryHash], cache);
}

return redisResults;
}

// Returns query name //
function findQueryName(query, startIdx = query.indexOf('{') + 1) {
console.log('query in findQueryName', query)
console.log(startIdx)
let i = startIdx;
let output = '';

Expand Down Expand Up @@ -170,4 +168,4 @@ function batchHash(propertySchema, hashPrefix) {
acc.push(fullQuery);
return acc;
}, [])
}
}
6 changes: 2 additions & 4 deletions src/hashOps.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


const findTypeSchemaName = hash => {
let i = 0;
while (hash[i] !== '~') {
Expand All @@ -10,7 +8,7 @@ const findTypeSchemaName = hash => {

const findProp = hash => {
let i = hash.length - 1;

while (hash[i] !== '~') {
i--;
}
Expand All @@ -20,4 +18,4 @@ const findProp = hash => {
export {
findTypeSchemaName,
findProp
}
}
Loading

0 comments on commit 3b14080

Please sign in to comment.