• Stars
    star
    139
  • Rank 262,954 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

GraphQL caching tool

DacheQL

Welcome to DacheQL a lightweight GraphQL caching tool utilizing Redis and LRU eviction policy. Feel free to check out our Medium article here.

Table of Contents
  1. Overview
  2. Prerequisites
  3. How to use our Demo
  4. Using our NPM package
  5. How does our LRU cache work
  6. Technologies used
  7. How to Contribute
  8. License
  9. Authors

Overview

DacheQL is an open-source developer tool that leverages the pinpoint accuracy of GraphQL's queries and implements caching to improve your website's query efficiency

Prerequisites

  • Before we divulge the prerequisites for using our npm package it should be noted that there are two different paths a developer can take when using our tool. The developer should decide whether or not they intend on utilizing Redis for its LFU (least frequently used) caching properties or if they would rather use our custom caching algorithm with its LRU (least recently used) behavior.
  • If you are going to use Redis please make sure you have installed Redis first.
  • Regardless of whether or not you are using Redis or our caching method, all developers will have to integrate GraphQL into their functionality. This means setting up your GraphQL schemas and resolvers as well as your database.
  • Finally, our package is intended to work in tandem with a full-stack application where the front end makes query requests to the backend, so please set this up as well before using our package.

How to use our Demo

  • At our website, if you would like to get a quick idea of how caching is beneficial head to our demo page.
  • Using our demo is a simple 3-step process.
  • First, choose your query of choose from our preset selection.
  • Press the run query button to see the resulting GraphQL query result. If you divert your attention to the metrics box down below you will see an uncached fetch time populate. This statistic represents the time it took to make a GraphQL fetch and receive the response data. You can also see the spike in time upwards on the graph provided on the right.
  • If you press the run query button again you will notice that your cached runtime metric will now render. The graph on the right will also dive down as the response time has significantly decreased. The uncached time should never change after this, as we are now retrieving your data from the cache every instance forward.

* *A small disclaimer: It should be noted that your first query will have a significantly higher runtime than the other first queries because it is establishing a connection.

Using our NPM package

Getting Started

If this is your first time using DacheQL, run the following command in your terminal:

npm install dacheql

In your server file, you want to require our middleware to handle GraphQL requests using the CommonJS format.

const dacheql = require('dacheql');

DacheQL functionality depends on Express' built-in method express.json() middleware function in order to parse incoming JSON payloads.

If you haven't already set up your server file with Express, add the following code to require Express:

const express = require('express');

Add the following code to construct an Express application based on a GraphQL schema:

const expressGraphQL = require('express-graphql').graphqlHTTP;

Add the following code to use the express.json() middleware function:

app.use(express.json());

Add the following code to obtain cached query results in the middleware function:

res.locals.queryResult;

Using DacheQL with Redis

DacheQL lets you decide if you would like to use Redis, or our custom LRU eviction cache. If you are using Redis, make sure you have Redis installed and your Redis server is running. To run Redis, type the following command in your terminal:

redis-cli

Once your Redis server is up and running, type PING into the terminal where your Redis server is running and you should receive a PONG response. If you get this response, you are ready to use DacheQL with Redis!

Now that your Redis server is up and running, in your backend server file, import Redis like so:

const redis = require('redis');

After importing Redis, you will have to create your Redis client which can be done as so:

const client = redis.createClient(REDIS_PORT);

Replace the text REDIS_PORT with your own Redis port (typically 6379).

Lastly, connect your client!

client.connect();

In order to cache your graphQL query responses, all you have to do is call our DacheQL function as middleware in your /graphql endpoint. The parameters for our function are as follows:

app.use(
    '/graphql', 
    dacheQL({ redis } = {<redis: client>}, capacity, endpoint, TTL),
    (req, res)=>{
      return res.status(200).send(res.locals.queryResult)
    }
  );

The first parameter is to let the function know whether you are using Redis or not as your cache. If you are, you will have to pass Redis into the function as {redis: client} like so.

The second parameter is the capacity for our custom LRU cache. If you are using Redis as your cache, just default to leaving the cache at 50.

The third parameter is the endpoint at which you are actually using GraphQL. For example, this endpoint may be http://localhost:3000/graphql.

Our last parameter is the Time to Live, or how long you want this specific query to last in your cache for. Pass in your time to live as seconds. Now you are good to cache your GraphQL responses!

Using DacheQL without Redis

If you are not using Redis caching, DacheQL provides a middleware for caching using the server's memory with our custom cache that behaves with an LRU eviction policy. The arguments you should input for this middlware are as follows:

For the first parameter, since you are not using Redis, simply pass in an empty object {} like so.

Next, is the capacity you would like your cache to hold. This capacity refers to when our cache will begin evicting items. For example, if you set the capacity to 50, it will evict an item upon the 51st unique query. It should be noted that if you pass in a non-whole number, it will be rounded down for you. Non integers, negative numbers, and capacities below two will default to simply creating a GraphQL fetch without storing values in the cache.

The third parameter is the endpoint at which you are actually using GraphQL. For example, this endpoint may be http://localhost:3000/graphql.

Our last parameter is the Time to Live, or how long you want this specific query to last in your cache for. Since we aren't using Redis here, just pass in anything for your TTL as our cache is not reliant on this information. Now you are good to cache your GraphQL responses!

app.use(
    '/graphql', 
    dacheQL({}, capacity, endpoint, TTL),
    (req, res)=>{
      return res.status(200).send(res.locals.queryResult)
    }
  );

Now, you have properly set up the middleware functions in order to use DacheQL's caching tools!

How does our LRU cache work?

  • Here's the breakdown of how the LRU caching algorithm works.
  • After ascertaining that the developer is not using Redis the first thing we do is consider all edge cases like invalid or missing URLs or capacities. If you pass an invalid URL you will be thrown an error as this is essential. With regard to the capacity, if you pass in a non-whole number, it will be rounded down for you. On the other hand, nonintegers, negative numbers, and capacities below 1 will default to simply creating a GraphQL fetch without storing values in the cache. Now we can get started.
  • Our algorithm utilizes object-orientated programming to devise a hashmap and linked list that work synergistically to maintain constant time (O1). We use the hashmap for its constant time in look-up and then we use the linked list for its constant time in updating, deletion, and creation. We have built several methods that accomplish functionality regarding how we delete and add to the LinkedList and the hashmap at the same time. There are also several methods that combine the previously devised methods to accomplish more specific tasks that will lead to our cache exhibiting LRU evicting behavior.
  • First, we deconstruct your query request from your request body for later use.
  • Put simply there are two more major scenarios we will check for. If your query is in our cache or not. If it isn't, we will fetch it for you and add the data to the front of the list and hashmap along with returning the query result to you. If it is in the cache we will update the hashmap and LinkedList by removing said item and reinstating it at the front of the linked list and return the query result to you.
  • When we update our list there is also the consideration of the capacity laid out and the size of our cache at this point. The whole point of evicting data from your cache is to keep your data predictable and maintainable so as to not pollute your memory. If you are attempting to add data onto the cache when the capacity isn't hit, it simply adds the data to the hashmap and the head of the linked list, where the most recently touched information sits. As a result, whatever is at the tail is the least recently touched data. Conversely, if you are trying to add data to the cache when you have hit your capacity we will evict the tail and remove it from the hashmap as well, before instating this new data as the new head of the linked list along with adding it to the map.

In the example above, you can see that we have run two queries for Pokemon and Cities respectively. For this instance, our capacity is set to 2. Those two queries and their respective data are shown above in our hashmap.

Here you can see those same two queries in the corresponding linkedlist.

With this photo, you can see we have run a new query for Valorant and its corresponding data is placed in the hashmap. Now since pokemon was the oldest query it has been evicted from the hashmap.

You can also see with this linked list Pokemon has been evicted as well.

  • Obviously, this is heavily simplified, but hopefully, this helps clear up the functionality of the LRU algorithm we use if you choose not to use Redis.

Technologies used

How to contribute

Here at DacheQL we created our open-source project with the intention to further expand upon and imprve this tool for years to come.

That's where the community comes in! If your have an idea that might make DacheQL better we always encourage contributions. Simply follow the steps below to submit the changes you would make.

  • Fork DacheQL
  • Pull down our dev branch with command (git pull origin dev)
  • Create your own Feature Branch with the command (git checkout -b <yourFeatureName>)
  • Add your changes with the command (git add .)
  • Stage and commit your changes with the command (git commit -m "<your comment>")
  • Merge your branch with the dev branch locally with the command (git merge dev)
  • Resolve any merge conflicts
  • Push up your branch with the command (git push origin <your feature branch name>)
  • Open a pull request
  • Don't forget to star this repo! We look forward to your contributions!

License

Distributed under the MIT license.

Authors

More Repositories

1

sapling

Sapling - A convenient way to traverse your React app in VS Code
JavaScript
489
star
2

Kafka-Sprout

🚀 Web GUI for Kafka Cluster Management
Java
429
star
3

GraphQuill

Real-time GraphQL API Exploration in VS Code
TypeScript
395
star
4

protographql

ProtoGraphQL is a prototyping tool that empowers developers to build and visualize GraphQL schemas and queries without writing any code.
JavaScript
360
star
5

seeql

see your database in a new way
TypeScript
344
star
6

Realize

A React component tree visualizer
JavaScript
327
star
7

Allok8

⚡️A pretty swell Kubernetes visualization tool
JavaScript
273
star
8

ReactRTC

NPM package that simplifies set-up of WebRTC as importable React components
JavaScript
270
star
9

svend3r

Interactive plug and play charting library for Svelte
JavaScript
267
star
10

aether

All-in-One Memory Leak Testing Solution
JavaScript
250
star
11

Yodelay

Your preferred gRPC endpoint testing tool. Making sure your outbound 🗣️ ‘yodelay’ returns the ‘IiiOoo’ 📣 that you expect
TypeScript
228
star
12

ReactRPC

Full feature integration library for gRPC-Web into React
JavaScript
224
star
13

atomos

Atomos is an open source dev tool for Recoil that provides real-time visualization of the component tree and atom-selector relationships to facilitate debugging of a React application.
JavaScript
218
star
14

Dockter

A low-overhead, open-source Docker log management tool
TypeScript
217
star
15

svelte-sight

A Svelte dev tool for visualizing component hierarchy, state, and props of your application
Svelte
215
star
16

KUR8

A visual overview of Kubernetes architecture and Prometheus metrics
JavaScript
213
star
17

OpticQL

Developer tool focused on streamlining the performance testing and optimization of GraphQL API
JavaScript
212
star
18

connext-js

A middleware and route handling solution for Next.js.
JavaScript
210
star
19

hypnos

The best way to test GraphQL calls to RESTful APIs.
JavaScript
205
star
20

Equa11y

A stream-lined command line tool for developers to easily run accessibility testing locally through axe-core and puppeteer.
TypeScript
204
star
21

preducks

React/Redux/Typescript Application Prototyping & Smart Boilerplate Generation Tool
TypeScript
199
star
22

drawql

an OSS tool for designing a graphql endpoint in Apollo
CSS
195
star
23

kubermetrics

JavaScript
194
star
24

TotalRecoilJS

TotalRecoilJS is a tool created to help developers visualize/debug and track their Recoil state via a Chrome extension.
JavaScript
193
star
25

Horus

🎯 A gRPC-Node Distributed Tracing and Monitoring Tool.
JavaScript
187
star
26

PostQL

Web app to visualize your GraphQL metrics and provide historical analytics
TypeScript
186
star
27

Ahoy

Ahoy! is a GUI tool for DevOps engineers which distills the many functions of Helm into a user-friendly interface.
JavaScript
183
star
28

battletest

A CLI module for npm that auto-generates tests based on user specified parameters.
JavaScript
183
star
29

Deno-Redlock

Deno's first lightweight, secure distributed lock manager utilizing the Redlock algorithm
TypeScript
182
star
30

ReactMonitor

Quickly visualize React's component tree and its performance
JavaScript
181
star
31

Osiris

An Electron based desktop application for generating components, building pages, and storing them in a UI library.
JavaScript
177
star
32

protostar-relay

Open-source iteration of the official Relay devtool.
JavaScript
171
star
33

TorchQL

A tool to quickly generate GraphQL schemas and resolvers from a relational database
JavaScript
171
star
34

trydent

testing tamed
TypeScript
170
star
35

genesisQL

rapid schema-prototyping tool for GraphQL applications
JavaScript
169
star
36

FilamentQL

GraphQL query and caching solution
JavaScript
168
star
37

GatsbyHub

Access everything Gatsby has to offer without ever leaving Visual Studio Code. This VSCode Extension allows you to generate a new Gatsby site using a starter, browse Gatsby plugins, and develop a server all with a click of a button.
TypeScript
163
star
38

aditum

Accessibility components for managing focus in React SPAs
JavaScript
162
star
39

watchmo

JavaScript
162
star
40

react-chronoscope

Developer tool to monitor React performance
JavaScript
162
star
41

navigate

A Kubernetes cluster visualizer for DevOps engineers - network policies, aggregated scheduler logs, deployments and pods before your cluster is running!
TypeScript
161
star
42

TrunQ

NPM package for easy client and/or server side graphQL caching.
JavaScript
160
star
43

onyx

Onyx is authentication middleware for Deno, inspired by Passport.js
TypeScript
159
star
44

BACE

JavaScript
159
star
45

MASH

Kafka visualizer and management suite
TypeScript
158
star
46

portara

Portara directive is a rate limiter / throttler for GraphQL
TypeScript
158
star
47

irisql

GraphQL prototyping tool to quickly mock-up Node API's and visualize where you can query from.
JavaScript
158
star
48

Interspect

An API mocking tool for testing data interoperability between microservices and secure HTTP endpoints
JavaScript
157
star
49

SMEE

JavaScript
154
star
50

ChaosQoaLa

Chaos Engineering meets GraphQL
JavaScript
153
star
51

VaaS

Modular Kubernetes Management System with OpenFaaS Support
TypeScript
153
star
52

tropicRPC

A VS Code extension that provides gRPC API endpoint testing.
TypeScript
153
star
53

dashport

Local and OAuth authentication middleware for Deno
TypeScript
151
star
54

anagraphql

JavaScript
151
star
55

Trinity

A VSCode extension for Cypher and Neo4j
TypeScript
150
star
56

DockerLocal

DockerLocal is a GUI application that allows you to keep an up-to-date version of the docker compose file for interconnected repositories while doing development work on a single repository.
TypeScript
150
star
57

giraffeQL

🦒 Developer tool to visualize relational databases and export schemas for GraphQL API's.
JavaScript
147
star
58

ProtoCAD

ProtoCAD is a prototyping tool that allows developers to build UI component tree structure based on GraphQL query results.
TypeScript
146
star
59

Trace

A lightweight GraphQL query performance monitoring GUI with real-time, resolver-level performance tracing metrics and error logging.
TypeScript
146
star
60

StratosDB

☄️ ☁️ An All-in-One GUI for Cloud SQL that can help users design and test their AWS RDS Instances
TypeScript
145
star
61

snAppy

snAppy is a VS Code extension coupled with an interactive view to support your React front-end delivery.
TypeScript
144
star
62

synapse

Realtime API Library
TypeScript
144
star
63

SpectiQL

GraphQL query, mutation, subscription test generator
JavaScript
143
star
64

starfleet

Command line tool to generate GraphQL services from Mongoose schemas with full CRUD functionality and deploy them to the cloud
JavaScript
143
star
65

pelican

Automated GUI canary testing for your kubernetes clusters
JavaScript
140
star
66

ProtoNative

A React Native prototyping tool for developers.
TypeScript
140
star
67

reactFLO

A Chrome DevTool built for developers to visualize the flow of state throughout their application.
TypeScript
140
star
68

ReactionTime

ReactionTime provides a simpler way to write tests for React's Experimental Concurrent Mode.
TypeScript
140
star
69

KuberOptic

An Electron app for developers to visualize their Kubernetes clusters in real-time
TypeScript
137
star
70

sono.land

Real-time Communication Library for Deno (WebSockets & WebRTC)
TypeScript
137
star
71

KubeScrape

KubeScrape: An open-source dev tool that provides an intuitive way to view the health, structure, and live metrics of your Kubernetes cluster
JavaScript
136
star
72

LucidQL

A developer tool and visualizer that generates a GraphQL schema from an established relational database.
JavaScript
135
star
73

Hookd

A cli tool and visualizer for converting React class components to functional components with hooks.
TypeScript
135
star
74

kr8s

Docker/Kubernetes Visualization Tool
JavaScript
133
star
75

Svelcro

Svelte DevTool with a focus on rendering
JavaScript
133
star
76

KnightOwl

An npm package of GraphQL middleware to protect you from malicious queries.
JavaScript
133
star
77

Palaemon

Palaemon is an open-source developer tool for monitoring health and resource metrics of Kubernetes clusters and analyzing Out of Memory (OOMKill) errors
TypeScript
133
star
78

SvelTable

Feature rich data table component.
Svelte
132
star
79

Ekkremis

A periscopic view into pending Kubernetes pods
TypeScript
132
star
80

kQ

TypeScript
131
star
81

fflow

fflow is an easy-to-use open-source tool for all developers to create their React application.
JavaScript
127
star
82

KlusterView

Get instant insights on your Kubernetes clusters with our lightweight, plug-and-play performance monitoring tool
TypeScript
125
star
83

Aqls-server

An intelligent full-stack GraphQL subscription and analytics module. Server-side analytics processing, self-auditing router, and resolver plugins.
JavaScript
123
star
84

kondo

JavaScript
123
star
85

periqles

React form library for Relay and Apollo
JavaScript
120
star
86

ThermaKube

A web application that monitors the health and performance of Kubernetes clusters with support for AWS EKS deployments
JavaScript
120
star
87

arteMetrics

Creating performance monitors for Apollo implementations of graphQL.
JavaScript
118
star
88

QLens

QLens is an electron app which dynamically generates GraphQL Schemas and Mongo Schema visualization. QLens significantly cuts development time by automating the formation of their GraphQL schemas based on information fetched from their non-relational database.
JavaScript
118
star
89

firecomm

A complete framework for gRPC-node.
JavaScript
117
star
90

Kafkasocks

JavaScript
114
star
91

ReaPer

Dev tool to analyze the performance of user interface and single-page applications based on the React frontend library
JavaScript
114
star
92

dangoDB

A MongoDB ODM for Deno
TypeScript
111
star
93

AtomicKafka

JavaScript
110
star
94

Bedrock

A modular authentication library for Deno.
TypeScript
110
star
95

Docklight

Metrics for your Docker containers
TypeScript
109
star
96

Neptune

A light-weight, simple, and straightforward learning tool for your Kubernetes cluster
JavaScript
109
star
97

ArtemisQL

ArtemisQL is a GraphQL migration tool and database visualizer that empowers developers to build and implement GraphQL with ease.
TypeScript
108
star
98

shipm8

JavaScript
108
star
99

ReacTree

ReacTree - VS Code extension that generates a hierarchy tree of React components with each node listing the passed down props, indicating whether it's connected the Redux store, and guiding you to the associated file with the click of a button
TypeScript
107
star
100

reactron

Reactron is a React component visualizer that allows you to traverse an app's fiber tree and render components individually.
JavaScript
105
star