跳转到内容
搜索文档

Workers 绑定(binding)

最后更新 查看 MarkdownAgent 设置

使用 Artifacts Workers 绑定(binding)直接从您的 Worker 中创建、导入、检查、分叉和删除存储库。Artifacts 绑定(binding)会返回存储库句柄,从而允许进行存储库范围的操作,例如令牌管理和分叉。

首先查看命名空间,然后选择要在本处绑定的命名空间名称。

配置绑定(binding)

将 Artifacts 绑定(binding)添加到您的 Wrangler 配置文件中:

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "artifacts": [
    {
      "binding": "ARTIFACTS",
      "namespace": "default"
    }
  ]
}
[[artifacts]]
binding = "ARTIFACTS"
namespace = "default" # replace with your Artifacts namespace
# remote = true # optional: use the remote Artifacts service in local dev

在您运行 npx wrangler types 之后,您的 Worker 环境将如下所示:

export interface Env {
	ARTIFACTS: Artifacts;
}

Wrangler 为使用者生成 Artifacts 类型,并将其直接绑定(bind)到您的环境中。

在命名的 Wrangler 环境中,artifacts 是不可继承的。在每个需要它的环境中重复该绑定(binding)。

在运行时,已部署的 Worker 会直接使用配置的绑定(binding)。对于本地 Wrangler 命令(如 wrangler devwrangler deploywrangler types),请先对 Wrangler 进行身份验证。关于本地 OAuth 身份验证,请参阅 wrangler login。关于 CI 或无头(headless)环境,请参阅 在 CI/CD 中运行 Wrangler

命名空间方法

env.ARTIFACTS 上使用命名空间方法来创建、列出、检查、导入或删除存储库。

create(name, opts?)

  • name RepoName必填
  • opts.readOnly boolean可选
  • opts.description string可选
  • opts.setDefaultBranch string可选
  • 返回 Promise<ArtifactsCreateRepoResult>

create() 返回存储库元数据,包括 nameremotedefaultBranch 和初始令牌。如果以后需要,请保存这些值。

async function createRepo(artifacts) {
	const created = await artifacts.create("starter-repo", {
		description: "Repository for automation experiments",
		readOnly: false,
		setDefaultBranch: "main",
	});

	return {
		defaultBranch: created.defaultBranch,
		name: created.name,
		remote: created.remote,
		initialToken: created.token,
	};
}
async function createRepo(artifacts: Artifacts) {
	const created = await artifacts.create("starter-repo", {
		description: "Repository for automation experiments",
		readOnly: false,
		setDefaultBranch: "main",
	});

	return {
		defaultBranch: created.defaultBranch,
		name: created.name,
		remote: created.remote,
		initialToken: created.token,
	};
}

get(name)

  • name RepoName必填
  • 返回 Promise<ArtifactsRepo>
  • 如果存储库不存在或尚未就绪,则抛出异常。

get() 返回现有存储库的句柄。使用该句柄可以调用存储库上的异步方法,例如 createToken()listTokens()revokeToken()fork()

async function getRepoHandle(artifacts) {
	const repo = await artifacts.get("starter-repo");
	const token = await repo.createToken("read", 3600);
	return token;
}
async function getRepoHandle(artifacts: Artifacts) {
	const repo = await artifacts.get("starter-repo");
	const token = await repo.createToken("read", 3600);
	return token;
}

list(opts?)

  • opts.limit number可选
  • opts.cursor Cursor可选
  • 返回 Promise<ArtifactsRepoListResult>
async function listRepos(artifacts) {
	const page = await artifacts.list({ limit: 10 });

	return {
		repos: page.repos.map((repo) => ({
			name: repo.name,
			status: repo.status,
		})),
		nextCursor: page.cursor ?? null,
	};
}
async function listRepos(artifacts: Artifacts) {
	const page = await artifacts.list({ limit: 10 });

	return {
		repos: page.repos.map((repo) => ({
			name: repo.name,
			status: repo.status,
		})),
		nextCursor: page.cursor ?? null,
	};
}

列出的每个存储库都包含一个 status 值,取值为 readyimportingforking

import(params)

从外部 git 远程端导入存储库。

  • params.source.url string必填 — 源存储库的 HTTPS URL。
  • params.source.branch string可选 — 要导入的分支(默认为远程端的默认分支)。
  • params.source.depth number可选 — 浅克隆(shallow clone)深度。
  • params.target.name RepoName必填 — 导入的存储库名称。
  • params.target.opts.description string可选
  • params.target.opts.readOnly boolean可选
  • 返回 Promise<ArtifactsCreateRepoResult>

import() 返回存储库元数据,包括 nameremotedefaultBranch 和初始令牌。如果以后需要,请保存 remotename 的值。

async function importFromGitHub(artifacts) {
	const imported = await artifacts.import({
		source: {
			url: "https://github.com/cloudflare/workers-sdk",
			branch: "main",
		},
		target: {
			name: "workers-sdk",
		},
	});

	return {
		name: imported.name,
		remote: imported.remote,
		token: imported.token,
	};
}
async function importFromGitHub(artifacts: Artifacts) {
	const imported = await artifacts.import({
		source: {
			url: "https://github.com/cloudflare/workers-sdk",
			branch: "main",
		},
		target: {
			name: "workers-sdk",
		},
	});

	return {
		name: imported.name,
		remote: imported.remote,
		token: imported.token,
	};
}

delete(name)

  • name RepoName必填
  • 返回 Promise<boolean>
async function deleteRepo(artifacts) {
	return artifacts.delete("starter-repo");
}
async function deleteRepo(artifacts: Artifacts) {
	return artifacts.delete("starter-repo");
}

存储库句柄方法

调用 await artifacts.get(name) 以获取存储库句柄。使用该句柄可以调用存储库上的异步方法。

createToken(scope?, ttl?)

  • scope "read" | "write"可选(默认:"write")
  • ttl number可选(秒)
  • 返回 Promise<ArtifactsCreateTokenResult>
async function mintReadToken(artifacts) {
	const repo = await artifacts.get("starter-repo");
	return repo.createToken("read", 3600);
}
async function mintReadToken(artifacts: Artifacts) {
	const repo = await artifacts.get("starter-repo");
	return repo.createToken("read", 3600);
}

create()import() 不同,repo.createToken() 返回一个包含 plaintextexpiresAt 的结构化结果。plaintext 值是 Git 令牌字符串。

listTokens()

  • 返回 Promise<ArtifactsTokenListResult>
async function listRepoTokens(artifacts) {
	const repo = await artifacts.get("starter-repo");
	const result = await repo.listTokens();
	return {
		total: result.total,
		tokens: result.tokens,
	};
}
async function listRepoTokens(artifacts: Artifacts) {
	const repo = await artifacts.get("starter-repo");
	const result = await repo.listTokens();
	return {
		total: result.total,
		tokens: result.tokens,
	};
}

revokeToken(tokenOrId)

  • tokenOrId string必填
  • 返回 Promise<boolean>
async function revokeToken(artifacts, tokenOrId) {
	const repo = await artifacts.get("starter-repo");
	return repo.revokeToken(tokenOrId);
}
async function revokeToken(artifacts: Artifacts, tokenOrId: string) {
	const repo = await artifacts.get("starter-repo");
	return repo.revokeToken(tokenOrId);
}

fork(name, opts?)

  • name RepoName必填
  • opts.description string可选
  • opts.readOnly boolean可选
  • opts.defaultBranchOnly boolean可选
  • 返回 Promise<ArtifactsCreateRepoResult>

fork() 返回新存储库的元数据。如果以后需要,请保存 remotename 的值。

async function forkRepo(artifacts) {
	const repo = await artifacts.get("starter-repo");
	const forked = await repo.fork("starter-repo-copy", {
		description: "Fork for testing",
		defaultBranchOnly: true,
		readOnly: false,
	});

	return forked.remote;
}
async function forkRepo(artifacts: Artifacts) {
	const repo = await artifacts.get("starter-repo");
	const forked = await repo.fork("starter-repo-copy", {
		description: "Fork for testing",
		defaultBranchOnly: true,
		readOnly: false,
	});

	return forked.remote;
}

log(opts?)

  • opts.ref string可选 — 分支、标签(tag)或提交哈希。
  • opts.limit number可选
  • opts.offset number可选
  • 返回 Promise<ArtifactsLogResult>
async function readCommitHistory(artifacts) {
	const repo = await artifacts.get("starter-repo");
	const history = await repo.log({ ref: "main", limit: 10 });
	return history;
}
async function readCommitHistory(artifacts: Artifacts) {
	const repo = await artifacts.get("starter-repo");
	const history = await repo.log({ ref: "main", limit: 10 });
	return history;
}

readCommit(hash)

  • hash string必填 — 提交 SHA-1 哈希。
  • 返回 Promise<ArtifactsCommit>
async function readCommit(artifacts, hash) {
	const repo = await artifacts.get("starter-repo");
	return repo.readCommit(hash);
}
async function readCommit(artifacts: Artifacts, hash: string) {
	const repo = await artifacts.get("starter-repo");
	return repo.readCommit(hash);
}

readTree(hash)

  • hash string必填 — 树(tree) SHA-1 哈希。
  • 返回 Promise<ArtifactsTree>
async function readTree(artifacts, hash) {
	const repo = await artifacts.get("starter-repo");
	return repo.readTree(hash);
}
async function readTree(artifacts: Artifacts, hash: string) {
	const repo = await artifacts.get("starter-repo");
	return repo.readTree(hash);
}

Worker 示例

该示例将绑定(binding)方法组合在一个 Worker 路由中。

src/index.jsjs
export default {
	async fetch(request, env) {
		const url = new URL(request.url);

		if (request.method === "POST" && url.pathname === "/repos") {
			const created = await env.ARTIFACTS.create("starter-repo");
			return Response.json({
				name: created.name,
				remote: created.remote,
			});
		}

		if (request.method === "POST" && url.pathname === "/tokens") {
			const repo = await env.ARTIFACTS.get("starter-repo");
			const token = await repo.createToken("read", 3600);
			return Response.json(token);
		}

		return Response.json(
			{ message: "Use POST /repos or POST /tokens." },
			{ status: 404 },
		);
	},
};
src/index.tsts
interface Env {
	ARTIFACTS: Artifacts;
}

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const url = new URL(request.url);

		if (request.method === "POST" && url.pathname === "/repos") {
			const created = await env.ARTIFACTS.create("starter-repo");
			return Response.json({
				name: created.name,
				remote: created.remote,
			});
		}

		if (request.method === "POST" && url.pathname === "/tokens") {
			const repo = await env.ARTIFACTS.get("starter-repo");
			const token = await repo.createToken("read", 3600);
			return Response.json(token);
		}

		return Response.json(
			{ message: "Use POST /repos or POST /tokens." },
			{ status: 404 },
		);
	},
} satisfies ExportedHandler<Env>;

生成的类型

在您自己的项目中运行 npx wrangler types,并将生成的 worker-configuration.d.ts 文件视为该环境中 Artifacts 绑定(binding)类型的唯一事实来源。

后续步骤

REST API

将绑定(binding)方法与底层 HTTP 路由进行比较。

开始使用 Workers

在从本地开发到部署的完整 Worker 项目中使用绑定(binding)。

Git 协议

在标准的 git-over-HTTPS 客户端中使用存储库远程端和令牌。

这篇文档对您有帮助吗?