Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: github driver #61

Merged
merged 6 commits into from
Jun 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ Comparing to similar solutions like [localforage](https://localforage.github.io/
- [`http` (universal)](#http-universal)
- [`redis`](#redis)
- [`cloudflare-kv`](#cloudflare-kv)
- [`github`](#github)
- [Making custom drivers](#making-custom-drivers)
- [Contribution](#contribution)
- [License](#license)
Expand Down Expand Up @@ -474,6 +475,35 @@ const storage = createStorage({
- `binding`: KV binding or name of namespace. Default is `STORAGE`.


### `github`

Map files from a remote github repository. (readonly)

This driver fetches all possible keys once and keep it in cache for 10 minutes. Because of github rate limit, it is highly recommanded to provide a token. It only applies to fetching keys.

```js
import { createStorage } from 'unstorage'
import githubDriver from 'unstorage/drivers/github'

const storage = createStorage({
driver: githubDriver({
repo: 'nuxt/framework',
branch: 'main',
dir: '/docs/content'
})
})
```

**Options:**

- **`repo`**: Github repository. Format is `username/repo` or `org/repo`. (Required!)
- **`token`**: Github API token. (Recommended!)
- `branch`: Target branch. Default is `main`
- `dir`: Use a directory as driver root.
- `ttl`: Filenames cache revalidate time. Default is `600` seconds (10 minutes)
- `apiURL`: Github API domain. Default is `https://api.github.com`
- `cdnURL`: Github RAW CDN Url. Default is `https://raw.githubusercontent.com`

## Making custom drivers

It is possible to extend unstorage by creating custom drives.
Expand Down
141 changes: 141 additions & 0 deletions src/drivers/github.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { defineDriver } from './utils'
import { $fetch } from 'ohmyfetch'
import { withTrailingSlash, joinURL } from 'ufo'

export interface GithubOptions {
/**
* The name of the repository. (e.g. `username/my-repo`)
* Required
*/
repo: string
farnabaz marked this conversation as resolved.
Show resolved Hide resolved
/**
* The branch to fetch. (e.g. `dev`)
* @default "main"
*/
branch: string
/**
* @default ""
*/
dir: string
/**
* @default 600
*/
ttl: number
/**
* Github API token (recommended)
*/
token?: string
/**
* @default "https://api.github.com"
*/
apiURL?: string
/**
* @default "https://raw.githubusercontent.com"
*/
cdnURL?: string
}

const defaultOptions: GithubOptions = {
repo: null,
branch: 'main',
ttl: 600,
dir: '',
apiURL: 'https://api.github.com',
cdnURL: 'https://raw.githubusercontent.com'
}

export default defineDriver((_opts: GithubOptions) => {
const opts = { ...defaultOptions, ..._opts }
const rawUrl = joinURL(opts.cdnURL, opts.repo, opts.branch, opts.dir)

let files = {}
let lastCheck = 0
let syncPromise: Promise<any>

if (!opts.repo) {
throw new Error('[unstorage] [github] Missing required option "repo"')
}

const syncFiles = async () => {
if ((lastCheck + opts.ttl * 1000) > Date.now()) {
return
}

if (!syncPromise) {
syncPromise = fetchFiles(opts)
}

files = await syncPromise
lastCheck = Date.now()
syncPromise = undefined
}

return {
async getKeys() {
await syncFiles()
return Object.keys(files)
},
async hasItem(key) {
await syncFiles()
return key in files
},
async getItem(key) {
await syncFiles()

const item = files[key]

if (!item) {
return null
}

if (!item.body) {
try {
item.body = await $fetch(key.replace(/:/g, '/'), {
baseURL: rawUrl,
headers: {
Authorization: opts.token ? `token ${opts.token}` : undefined
}
})
} catch (err) {
throw new Error(`[unstorage] [github] Failed to fetch "${key}"`, { cause: err })
}
}
return item.body
},
async getMeta(key) {
await syncFiles()
const item = files[key]
return item ? item.meta : null
}
}
})

async function fetchFiles(opts: GithubOptions) {
const prefix = withTrailingSlash(opts.dir)
const files = {}
try {
const trees = await $fetch(`/repos/${opts.repo}/git/trees/${opts.branch}?recursive=1`, {
baseURL: opts.apiURL,
headers: {
Authorization: opts.token ? `token ${opts.token}` : undefined
}
})

for (const node of trees.tree) {
if (node.type !== 'blob' || !node.path.startsWith(prefix)) {
continue
}
const key = node.path.substring(prefix.length).replace(/\//g, ':')
files[key] = {
meta: {
sha: node.sha,
mode: node.mode,
size: node.size
farnabaz marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
} catch (err) {
throw new Error(`[unstorage] [github] Failed to fetch git tree`, { cause: err })
}
return files
}