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

@zen_flow/next-tinacms-github

v0.35.0-zenflow.2

Published

This package provides helpers for managing the **GitHub auth token** for requests, as well as providing helpers for **loading content from the Github API**.

Downloads

5

Readme

next-tinacms-github

This package provides helpers for managing the GitHub auth token for requests, as well as providing helpers for loading content from the Github API.

Installation

yarn add next-tinacms-github

Any functions in the pages/api directory are mapped to /api/* endpoints. The below helpers tend to be added to the pages/api directory in a Next.js project.

authHandler

Helper for creating a authHandler server function.

pages/api/create-github-access-token.ts

import { createAuthHandler } from 'next-tinacms-github'

export default createAuthHandler(
  process.env.GITHUB_CLIENT_ID,
  process.env.GITHUB_CLIENT_SECRET,
  process.env.SIGNING_KEY
)

See Next's documentation for adding environment variables

See here for instructions on creating a Github OAuth App to generate these Client ID & Client Secret variables and setting up the Signing Key.

apiProxy

Proxies requests to GitHub, attaching the GitHub access token in the process.

pages/api/proxy-github.ts

import { apiProxy } from 'next-tinacms-github'

export default apiProxy(process.env.SIGNING_KEY)

previewHandler

Handles setting the the Nextjs preview data from your cookie data.

pages/api/preview.ts

import { previewHandler } from 'next-tinacms-github'

export default previewHandler(process.env.SIGNING_KEY)

Loading content from Github

The preview data, which gets set by calling your preview function, will be accessible through getStaticProps throughout your app.

Below is an example of the conditional data fetching, from the local environment or Working GitHub Repository based on the preview environment:

/blog/slug.ts

import {
  getGithubPreviewProps
  parseMarkdown,
} from 'next-tinacms-github'

// ...

export const getStaticProps: GetStaticProps = async function({
  preview,
  previewData,
  ...ctx
}) {
  if (preview) {
    return getGithubPreviewProps({
      ...previewData,
      fileRelativePath: 'src/content/home.json',
      parse: parseMarkdown
    });
  }
  return {
    props: {
      error: null,
      preview,
      file: {
        fileRelativePath: 'src/content/home.json',
        data: (await import('../content/home.json')).default,
      },
    },
  };
}

getGithubPreviewProps

The getGithubPreviewProps function accepts this preview data:

interface PreviewData<Data> {
  github_access_token: string
  working_repo_full_name: string
  head_branch: string
  fileRelativePath: string
  parse(content: string): Data
}

It then fetches the content from the Working GitHub Repository and returns a props object with this shape:

return {
  props: {
    file,
    repoFullName: workingRepoFullName,
    branch: headBranch,
    preview: true,
    error,
  },
}

_getGithubFile

In some cases you'll need to load multiple files from Github. For this reason the underlying getGithubFile function is exposed.

import {
  getGithubFile,
  parseJson,
  parseMarkdown,
} from 'next-tinacms-github'

export const getStaticProps: GetStaticProps = async function({
  preview,
  previewData,
  ...ctx
}) {
  const githubOptions = {
    repoFullName: previewData?.working_repo_full_name || 'https://github.com/youre/respository',
    branch: previewData?.head_branch || 'master',
    accessToken: previewData?.github_access_token || '',
  }

  const homeFile = await getGithubFile({
    ...githubOptions,
    fileRelativePath: "content/index.md
    parse: parseMarkdown
  })

  const navigationFile = await getGithubFile({
    ...githubOptions,
    fileRelativePath: "data/navigation.json
    parse: parseJson
  })

  return {
    preview,
    homeFile,
    navigationFile,
  }
}

Parsing Data

next-tinacms-github provides two content parsing options available, for Markdown — parseMarkdown or JSON — parseJson. Or you could pass in a custom parser.

NextGithubMediaStore

next-tinacms-github includes a media store for managing media files with GitHub. Based on GithubMediaStore, it includes logic for serving uploads from the public/ directory.

This media store is initialized similar to GithubMediaStore:

import { TinaCMS } from 'tinacms'
import { GithubClient } from 'react-tinacms-github'
import { NextGithubMediaStore } from 'next-tinacms-github'

const githubClient = new GithubClient({
  proxy: '/api/proxy-github',
  authCallbackRoute: '/api/create-github-access-token'
  clientId: process.env.GITHUB_CLIENT_ID,
  baseRepoFullName: process.env.REPO_FULL_NAME
})

const mediaStore = new NextGithubMediaStore(githubClient)

const cms = new TinaCMS({
  apis: {
    github: githubClient // equivalent to cms.registerApi('github', githubClient)
  },
  media: mediaStore
})

previewSrc

NextGithubMediaStore handles previewSrc so you shouldn't need to set this on individual image fields. However, if you do need to override previewSrc for a specific field, you need to get the full url to the source GitHub repository. The return value should connect to an actual path in a GitHub repo where the image is hosted.

// Exmaple image field config
const formOptions = {
  fields: [
    {
      label: 'Hero Image',
      name: 'frontmatter.hero_image',
      component: 'image',
      parse: media => `/${media.filename}`,
      uploadDir: () => '/public/',
      previewSrc: fieldValue => {
        const githubClient = useGithubClient()

        return githubClient.getDownloadUrl(path.join('public', fieldValue))
      },
    },
  ],
  //...
}

The reason why the full GitHub url needs to be provided is that new images are uploaded to the repository on a particular branch. If you are working locally, this can be a bit confusing because the path saved to the source file will be different than this previewSrc url. Remember when developing locally with this package that previewSrc urls are connecting to GitHub repository and not your local file paths.

You still need to set uploadDir to 'public' if you want the media manager to open directly from that folder, otherwise it will open from and upload to the repository root.