-
Notifications
You must be signed in to change notification settings - Fork 135
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: add uploadthing driver #390
Open
juliusmarminge
wants to merge
9
commits into
unjs:main
Choose a base branch
from
juliusmarminge:ut-driver
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4cb6acf
init
juliusmarminge cac6a06
nit
juliusmarminge f9a5a15
rm getItems
juliusmarminge 8d46dab
track internal keys
juliusmarminge 6444a42
fix
juliusmarminge e98edab
remove my apikey
juliusmarminge 4d55f54
stub out docs
juliusmarminge 4c9a188
use custom ids
juliusmarminge a54c648
ref
juliusmarminge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -92,6 +92,7 @@ | |
"types-cloudflare-worker": "^1.2.0", | ||
"typescript": "^5.3.3", | ||
"unbuild": "^2.0.0", | ||
"uploadthing": "^6.3.0", | ||
"vite": "^5.0.11", | ||
"vitest": "^1.2.1", | ||
"vue": "^3.4.14" | ||
|
@@ -108,7 +109,8 @@ | |
"@planetscale/database": "^1.13.0", | ||
"@upstash/redis": "^1.28.1", | ||
"@vercel/kv": "^0.2.4", | ||
"idb-keyval": "^6.2.1" | ||
"idb-keyval": "^6.2.1", | ||
"uploadthing": "^6.0.0" | ||
}, | ||
"peerDependenciesMeta": { | ||
"@azure/app-configuration": { | ||
|
@@ -146,6 +148,9 @@ | |
}, | ||
"idb-keyval": { | ||
"optional": true | ||
}, | ||
"uploadthing": { | ||
"optional": true | ||
} | ||
}, | ||
"packageManager": "[email protected]" | ||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
import { defineDriver } from "./utils"; | ||
import { ofetch, $Fetch } from "ofetch"; | ||
import { UTApi } from "uploadthing/server"; | ||
|
||
export interface UploadThingOptions { | ||
apiKey: string; | ||
} | ||
|
||
export default defineDriver<UploadThingOptions>((opts) => { | ||
let client: UTApi; | ||
let utApiFetch: $Fetch; | ||
let utFsFetch: $Fetch; | ||
|
||
const internalToUTKeyMap = new Map<string, string>(); | ||
const fromUTKey = (utKey: string) => { | ||
for (const [key, value] of internalToUTKeyMap.entries()) { | ||
if (value === utKey) { | ||
return key; | ||
} | ||
} | ||
}; | ||
|
||
const getClient = () => { | ||
return (client ??= new UTApi({ | ||
apiKey: opts.apiKey, | ||
fetch: ofetch.native, | ||
logLevel: "debug", | ||
})); | ||
}; | ||
|
||
// The UTApi doesn't have all methods we need right now, so use raw fetch | ||
const getUTApiFetch = () => { | ||
return (utApiFetch ??= ofetch.create({ | ||
method: "POST", | ||
baseURL: "https://uploadthing.com/api", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would it makes sense to support an optional option for baseURL? (mainly to allow unit testing) |
||
headers: { | ||
"x-uploadthing-api-key": opts.apiKey, | ||
}, | ||
})); | ||
}; | ||
|
||
const getUTFsFetch = () => { | ||
return (utFsFetch ??= ofetch.create({ | ||
baseURL: "https://utfs.io/f", | ||
})); | ||
}; | ||
|
||
return { | ||
hasItem(key) { | ||
const utkey = internalToUTKeyMap.get(key); | ||
if (!utkey) return false; | ||
// This is the best endpoint we got currently... | ||
return getUTApiFetch()("/getFileUrl", { | ||
body: { fileKeys: [utkey] }, | ||
}).then((res) => { | ||
return !!res?.data?.length; | ||
}); | ||
}, | ||
getItem(key) { | ||
const utkey = internalToUTKeyMap.get(key); | ||
if (!utkey) return null; | ||
return getUTFsFetch()(`/${utkey}`).then((r) => r.text()); | ||
}, | ||
getKeys() { | ||
return getClient() | ||
.listFiles({}) | ||
pi0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.then((res) => res.map((file) => fromUTKey(file.key) ?? file.key)); | ||
}, | ||
setItem(key, value, opts) { | ||
return getClient() | ||
.uploadFiles(Object.assign(new Blob([value]), { name: key }), { | ||
metadata: opts?.metadata, | ||
}) | ||
.then((response) => { | ||
if (response.error) throw response.error; | ||
internalToUTKeyMap.set(key, response.data.key); | ||
}); | ||
}, | ||
setItems(items, opts) { | ||
return getClient() | ||
.uploadFiles( | ||
items.map((item) => | ||
Object.assign(new Blob([item.value]), { name: item.key }) | ||
), | ||
{ metadata: opts?.metadata } | ||
) | ||
.then((responses) => { | ||
responses.map((response) => { | ||
if (response.error) throw response.error; | ||
internalToUTKeyMap.set(response.data.name, response.data.key); | ||
}); | ||
}); | ||
}, | ||
removeItem(key, opts) { | ||
const utkey = internalToUTKeyMap.get(key); | ||
if (!utkey) throw new Error(`Unknown key: ${key}`); | ||
return getClient() | ||
.deleteFiles([utkey]) | ||
.then(() => { | ||
internalToUTKeyMap.delete(key); | ||
}); | ||
}, | ||
async clear() { | ||
const utkeys = Array.from(internalToUTKeyMap.values()); | ||
return getClient() | ||
.deleteFiles(utkeys) | ||
.then(() => { | ||
internalToUTKeyMap.clear(); | ||
}); | ||
}, | ||
|
||
// getMeta(key, opts) { | ||
// // TODO: We don't currently have an endpoint to fetch metadata, but it does exist | ||
// }, | ||
}; | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
import { afterAll, beforeAll, describe, it } from "vitest"; | ||
import driver from "../../src/drivers/uploadthing"; | ||
import { testDriver } from "./utils"; | ||
import { setupServer } from "msw/node"; | ||
import { rest } from "msw"; | ||
|
||
const store: Record<string, any> = {}; | ||
|
||
const utapiUrl = "https://uploadthing.com/api"; | ||
const utfsUrl = "https://utfs.io/f"; | ||
|
||
const server = setupServer( | ||
rest.post(`${utapiUrl}/getFileUrl`, async (req, res, ctx) => { | ||
const { fileKeys } = await req.json(); | ||
const key = fileKeys[0]; | ||
if (!(key in store)) { | ||
return res(ctx.status(401), ctx.json({ error: "Unauthorized" })); | ||
} | ||
return res( | ||
ctx.status(200), | ||
ctx.json({ | ||
result: { | ||
[key]: `https://utfs.io/f/${key}`, | ||
}, | ||
}) | ||
); | ||
}), | ||
rest.get(`${utfsUrl}/:key`, (req, res, ctx) => { | ||
const key = req.params.key as string; | ||
if (!(key in store)) { | ||
return res(ctx.status(404), ctx.json(null)); | ||
} | ||
return res( | ||
ctx.status(200), | ||
ctx.set("content-type", "application/octet-stream"), | ||
ctx.body(store[key]) | ||
); | ||
}), | ||
rest.post(`${utapiUrl}/uploadFiles`, async (req, res, ctx) => { | ||
console.log("intercepted request"); | ||
return res( | ||
ctx.status(200), | ||
ctx.json({ | ||
data: [ | ||
{ | ||
presignedUrls: [`https://my-s3-server.com/:key`], | ||
}, | ||
], | ||
}) | ||
); | ||
}), | ||
rest.post(`${utapiUrl}/deleteFile`, async (req, res, ctx) => { | ||
console.log("hello????"); | ||
const { fileKeys } = await req.json(); | ||
for (const key of fileKeys) { | ||
delete store[key]; | ||
} | ||
return res(ctx.status(200), ctx.json({ success: true })); | ||
}) | ||
); | ||
|
||
describe( | ||
"drivers: uploadthing", | ||
() => { | ||
// beforeAll(() => { | ||
// server.listen(); | ||
// }); | ||
// afterAll(() => { | ||
// server.close(); | ||
// }); | ||
|
||
testDriver({ | ||
driver: driver({ | ||
apiKey: | ||
"sk_live_4603822c7c4574cc90495ff3b31204adf20311bc953903d8081be7a5176f31aa", | ||
}), | ||
async additionalTests(ctx) {}, | ||
}); | ||
}, | ||
{ timeout: 30e3 } | ||
); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.