Skip to content

Commit ea0e2bc

Browse files
committed
add repoExists function
1 parent 0be6a40 commit ea0e2bc

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

packages/hub/src/lib/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export * from "./oauth-handle-redirect";
2323
export * from "./oauth-login-url";
2424
export * from "./parse-safetensors-metadata";
2525
export * from "./paths-info";
26+
export * from "./repo-exists";
2627
export * from "./snapshot-download";
2728
export * from "./space-info";
2829
export * from "./upload-file";
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { describe, expect, it } from "vitest";
2+
import { repoExists } from "./repo-exists";
3+
4+
describe("repoExists", () => {
5+
it("should check if a repo exists", async () => {
6+
const exists1 = await repoExists({ repo: { type: "model", name: "openai-community/gpt2" } });
7+
8+
expect(exists1).toBe(true);
9+
10+
const exists2 = await repoExists({ repo: { type: "model", name: "openai-community/gpt9000" } });
11+
expect(exists2).toBe(false);
12+
});
13+
});
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { HUB_URL } from "../consts";
2+
import { createApiError } from "../error";
3+
import type { RepoDesignation } from "../types/public";
4+
import { toRepoId } from "../utils/toRepoId";
5+
6+
export async function repoExists(params: {
7+
repo: RepoDesignation;
8+
9+
hubUrl?: string;
10+
/**
11+
* An optional Git revision id which can be a branch name, a tag, or a commit hash.
12+
*/
13+
revision?: string;
14+
/**
15+
* Custom fetch function to use instead of the default one, for example to use a proxy or edit headers.
16+
*/
17+
fetch?: typeof fetch;
18+
accessToken?: string;
19+
}): Promise<boolean> {
20+
const repoId = toRepoId(params.repo);
21+
22+
const res = await (params.fetch ?? fetch)(
23+
`${params.hubUrl ?? HUB_URL}/api/${repoId.type}s/${repoId.name}?expand[]=likes`,
24+
{
25+
method: "GET",
26+
headers: {
27+
...(params.accessToken && {
28+
Authorization: `Bearer ${params.accessToken}`,
29+
}),
30+
},
31+
}
32+
);
33+
34+
if (res.status === 404 || res.status === 401) {
35+
return false;
36+
}
37+
38+
if (!res.ok) {
39+
throw await createApiError(res);
40+
}
41+
42+
return true;
43+
}

0 commit comments

Comments
 (0)