Are you looking for a free and quick to set up service to persist (temporary) data? This article is for you. You've probably used gists before, but how about using one as a data storage?
Here's the easiest setup for storing information for small hobby projects. Yeah, it goes without saying โย this isn't a real database nor something you should use for production applications. However, for hobby projects, this is an easy and completely free way to store information.
Something worth mentioning is that the data you store in secret gists is available in the public without authentication so this is not a good place to store any secrets.
I'm using this approach in a few of my projects to store not-that-critical information like the channels my chatbot is in or the reminder data of a Reddit reminder bot.
Here's how it works
- Create a new secret gist
- Create a file called db.json inside of it. Make it an empty object
{}
. - Get yourself a personal Github access token here.
gist
is the only scope you should need.
const TOKEN = "YOUR_PERSONAL_ACCESS_TOKEN";
const GIST_ID = "YOUR_GIST_ID";
const GIST_FILENAME = "db.json";
/*
* Reads the JSON file inside of the gist
*/
async function getData() {
const req = await fetch(`https://api.github.com/gists/${GIST_ID}`);
const gist = await req.json();
return JSON.parse(gist.files[GIST_FILENAME].content);
}
/*
* Puts the data you want to store back into the gist
*/
async function setData(data) {
const req = await fetch(`https://api.github.com/gists/${GIST_ID}`, {
method: "PATCH",
headers: {
Authorization: `Bearer ${TOKEN}`,
},
body: JSON.stringify({
files: {
[GIST_FILENAME]: {
content: JSON.stringify(data),
},
},
}),
});
return req.json();
}
Top comments (0)