Skip to content

Commit

Permalink
Merge pull request #35 from mmeigs/master
Browse files Browse the repository at this point in the history
Added mutation handling
  • Loading branch information
CaliskanBurak authored Sep 21, 2020
2 parents 32da0a3 + f11fd7a commit 1c85251
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 8 deletions.
24 changes: 23 additions & 1 deletion ObsidianWrapper/ObsidianWrapper.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,31 @@ function ObsidianWrapper(props) {
? sessionStorage.setItem(query, JSON.stringify(response))
: setCache(newObj);
}

function clearCache() {
sessionStorage.clear();
setCache({});
}

async function mutate(mutation, options = {}) {
const { endpoint = '/graphql', clearCache = true } = options;
try {
const respJSON = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ query: mutation }),
});
const resp = await respJSON.json();
if (clearCache) clearCache();
return resp;
} catch (e) {
console.log(e);
}
}

// Excecutes graphql fetch request
async function hunt(query, endpoint, destructure, sessionStore) {
try {
Expand Down Expand Up @@ -130,9 +150,11 @@ function ObsidianWrapper(props) {
}
}



// Returning Provider React component that allows consuming components to subscribe to context changes
return (
<cacheContext.Provider value={{ cache, gather, hunt, clearCache }} {...props} />
<cacheContext.Provider value={{ cache, gather, hunt, mutate, clearCache }} {...props} />
);
}
// Declaration of custom hook to allow access to provider
Expand Down
20 changes: 20 additions & 0 deletions demo/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ type Query {
getBook(id: ID): Book!
getEightBooks(id: ID): [Book]
}
type Mutation {
updateAuthor(id: ID!, author: String!): Book
}
`;

// GraphQL Resolvers (For now just the basic getBooks query)
Expand Down Expand Up @@ -174,6 +178,22 @@ const resolvers = {
return books;
},
},
Mutation: {
updateAuthor: async (parent: any, { id, author }: any, context: any, info: any) => {
try {
const resp = await client.query(`
UPDATE books
SET author = $1
WHERE id = $2
`, author, id);

return resp;
} catch (err) {
console.log('mutation error', err)
return err;
}
}
}
};

interface ObsRouter extends Router {
Expand Down
11 changes: 10 additions & 1 deletion src/dbOps.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,20 @@ async function retrieveComplex(hash, cache) {
}
}

async function clearRedis() {
if (!redis) redis = await connectFunc(browser);
redis.flushdb(function (err, succeeded) {
if (err) console.log('redis error ', err)
console.log(succeeded); // will be true if successfull
});
}



export {
checkAndInsert,
checkAndRetrieveQuery,
retrieveScalar,
retrieveComplex
retrieveComplex,
clearRedis
}
19 changes: 18 additions & 1 deletion src/destructureQueries.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import specificQueryParser from './specificQueryParser.js';
import { checkAndRetrieveQuery, retrieveScalar, retrieveComplex } from './dbOps.js';
import { checkAndRetrieveQuery, retrieveScalar, retrieveComplex, clearRedis } from './dbOps.js';
import createQueryObj from './createQueryObj.js';
import { findTypeSchemaName, findProp } from './hashOps.js';

Expand All @@ -10,6 +10,11 @@ export default async function destructureQueries(query, obsidianSchema, cache) {

// Destructure query into array of minified sub-queries //
const queryHashes = await findSpecificQueries(query, obsidianSchema, cache);
// If graphql query is a mutation, clear Redis and skip destructuring //
if (!queryHashes) {
clearRedis();
return 'mutation';
}

const result = {
data: {}
Expand Down Expand Up @@ -107,6 +112,8 @@ async function findSpecificQueries(query, obsidianSchema, cache) {

// Finds first query name //
let nameOfQuery = findQueryName(query);
// If graphql query is a mutation //
if (nameOfQuery === 'mutation') return undefined;

// Iterates until all sub-queries are added to queryHashes object //
while (nameOfQuery) {
Expand All @@ -131,6 +138,12 @@ function findQueryName(query, startIdx = query.indexOf('{') + 1) {
let i = startIdx;
let output = '';

if (startIdx > 6) {
if (query.slice(0, startIdx).includes('mutation')) {
return 'mutation';
}
}

while (i < query.length) {
// Eat whitespace
if (query[i] === ' ') {
Expand All @@ -145,6 +158,10 @@ function findQueryName(query, startIdx = query.indexOf('{') + 1) {
} else if (query[i] === '(' || query[i] === '{') {
return output;
} else {
if (query[i] === 'm' && query.slice(i, i+7) === 'mutation') {
return 'mutation';
}

// Edge case for query string beginning with redundant 'query' //
if (query[i] === 'q' && query.slice(i,i+5) === 'query') {
i = query.indexOf('{') + 1;
Expand Down
13 changes: 8 additions & 5 deletions src/obsidian.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,16 @@ export async function ObsidianRouter<T>({

console.log('Incoming Query:');
console.log(body.query);
let toNormalize = true;

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)
// 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)

if (obsidianReturn === 'mutation') toNormalize = false;

if (obsidianReturn) {
if (obsidianReturn && obsidianReturn !== 'mutation') {
response.status = 200;
response.body = obsidianReturn;

Expand All @@ -92,7 +95,7 @@ export async function ObsidianRouter<T>({
console.log(result);
console.log('Sending results off to normalize...')

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

return;
} catch (error) {
Expand Down

0 comments on commit 1c85251

Please sign in to comment.