npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@vighnesh153/github-gist

v0.4.7

Published

A simple promise-based wrapper over the GitHub's REST API to play with GitHub Gists.

Downloads

8,699

Readme

GitHub Gist REST API Wrapper

npm npm bundle size (scoped) npm (scoped) GitHub GitHub issues

A simple promise-based wrapper over the GitHub's REST API to play with GitHub Gists.

Installation

npm install @vighnesh153/github-gist

# Peer dependency
npm install axios

Before you begin

To interact with the gist in your GitHub account, you need to create a Personal Access Token with the gist scope.

  • Generate your token
  • Create a GitHub Gist by visiting this link. You might have to create a dummy file because GitHub doesn't allow you to create empty gist. Once you have created the gist, note down the gist id (found in the url)
  • CORS configuration (if you are using this on a browser): The GET API to fetch the content of a file in a gist, is CORS protected. If you are using this library on a browser, then you will get CORS blocked. To prevent that, I have added a default CORS proxy server configuration https://corsanywhere.herokuapp.com/. But, it is not a good idea to use this default in production because it probably isn't reliable. The owner might decide to shut it down anytime. So, I recommend you to build/host your own proxy or opt in for a more reliable one. Following are some helpful links (I found these options via a quick google search and these are just to get you started and not my recommendations):
    • A cheap paid service option: https://cors.sh/
    • Host one of the following proxy server code on your platform of choice
      • https://github.com/ccoenraets/cors-proxy/blob/master/server.js
    • Create your own CORS proxy from scratch
      • Way 1: https://dev.to/decker67/write-your-own-cors-proxy-with-nodejs-in-no-time-30f9
      • Way 2: https://medium.com/nodejsmadeeasy/a-simple-cors-proxy-for-javascript-applications-9b36a8d39c51

Usage

Importing

  • Import/Export
import { GithubGist } from '@vighnesh153/github-gist';
  • Require
const { GithubGist } = require('@vighnesh153/github-gist');
  • As a script tag (UMD modules)
<!--More on JS Deliver: https://www.jsdelivr.com/-->
<script src="https://cdn.jsdelivr.net/npm/@vighnesh153/github-gist/dist/main.umd.js"></script>

<script>
  const GithubGist = GithubGistUmd.GithubGist;

  // rest of the code below
</script>

Instantiation

const gist = await GithubGist.initializeUsingGistId({
  // Required
  personalAccessToken: '<GITHUB_PERSONAL_ACCESS_TOKEN>',

  // Required
  gistId: '<YOUR-GIST-ID>',

  // --- OPTIONAL PARAMS BELOW ---

  // Since the gist is also commit based, we can cache the GET urls because git guarantees that
  // if the content changes, its SHA will also change which will lead to a new URL for latest content
  // If you have lot of gists and you think that caching all the files will be heavy, you can disable
  // caching by setting it to false
  enableRequestCaching: true,

  // Whether the Gist will be a public gist or a secret gist. Note that secret gists are still
  // accessible via URLs
  isPublic: false,

  // Content GET url is CORS protected and we cannot use it directly on the frontend. So, by default,
  // we add a Proxy configuration to bypass CORS protection
  //
  // If you are running this on a server/backend, you can set it to `{ type: 'none' }`
  //
  // If you want to configure CORS manually, you can use the third type:
  // `{ type: 'custom', customRequestConfig: (url) => AxiosRequestConfig }`
  //
  corsConfig: { type: 'default' },
});

Files in Gist

A gist can have multiple files. To create a file, do the following:

You can only store string content in a file. So, if you are creating a JSON file, remember to stringify the content

const pikachuJson = gist.createNewFile('pikachu.json');

console.log(pikachuJson.content);
// ''

pikachuJson.content = JSON.stringify({ message: 'Pikachu is the best' });

console.log(JSON.parse(pikachuJson.content));
// { message: "Pikachu is the best" }

Save a file

Just creating the file won't save it on your GitHub Gist. To save, you will have to invoke the save() method on it

// This will save the file on the Gist
await pikachuJson.save();

Save multiple files at once

If you have multiple new files or modified files, you can invoke save() on the gist itself to save all the files in a single HTTP request

const pikachuPython = gist.createNewFile('pikachu.py');
pikachuPython.content = `print("Pikachu is the best")`;

const pikachuJs = gist.createNewFile('pikachu.js');
pikachuJs.content = `console.log("Pikachu is the best")`;

// Saves all files in a single request
await gist.save();

Get an existing file

You can access the previously created file by doing the following

const existingPikachuJson = gist.getFileByName('pikachu.json');

Alternatively, you can also use createNewFile which will return the existing file, if it exists, else, create it and return it.

const existingPikachuJson = gist.createNewFile('pikachu.json');

Fetch the latest content of a gist

If you suspect that your local gist instance is out of date with the actual GitHub Gist, you can fetch the latest content

// Entire gist
await gist.fetchLatestContent();

// Specific file
await pikachuJson.fetchLatestContent();

Get all the files

const files = gist.files;

Get the owner of the gist

const ownerLogin = gist.owner;

Things to be aware of

Gist is an awesome way to store small amount data without having to spin up a database. But it does come with some caveats.

  • You cannot use it in a multi-threaded application because all the save requests are force pushes, and you could overwrite other thread's changes
  • Requests are not atomic
  • Don't invoke save in parallel. Wait for the previous Promise to resolve completely before starting the next one.