dvanderburg/lumen-batched-request

Lumen框架(Laravel PHP)批量请求的服务提供商。

dev-master 2018-11-05 14:11 UTC

This package is not auto-updated.

Last update: 2024-09-20 23:18:49 UTC


README

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

Lumen批量请求服务提供商。使用方法和实现大致基于Facebook Graph API的批量请求

批量请求允许您同时发送多个请求,使您能够在单个HTTP请求中执行多个操作。除非指定了依赖关系,否则批处理中的每个请求将按顺序处理。

批处理中的请求可以列出其他请求的依赖关系,并通过JSONP语法访问其响应。再次,类似于Facebook的Graph API。使用JSONP语法,批处理中的请求可以使用另一个请求的响应。更多信息请参阅使用和示例部分。

一旦所有请求都已完成,将返回一个响应数组,并关闭HTTP连接。

基于PHP 7.1.13和Laravel框架Lumen(5.6.3)构建。

依赖

安装和设置

通过composer安装包。

composer install dvanderburg/lumen-batched-request

在app.php中注册服务提供商

$app->register(Dvanderburg\BatchedRequest\BatchedRequestServiceProvider::class);

简单批量请求

通过向/batch/发送HTTP POST来发送基本的批量请求。此示例将执行两个GET请求和一个POST请求,并返回一个响应数组。

HTTP POST示例

POST /batch HTTP/1.1
Content-Type: application/json
batch: [
	{ method: "GET",	relative_url: "/product/1234" },
	{ method: "GET",	relative_url: "/user/?ids=larry,jill,sally" },
	{ method: "POST",	'content-type': "application/x-www-form-urlencoded", name: 'create-user', relative_url: "/user/?username=john" body: "password=admin"},

Axios XHR示例

axios.post('/batch', {
	batch: [
		{ method: "GET",	relative_url: "/product/1234" },
		{ method: "GET",	relative_url: "/user/?ids=larry,jill,sally" },
		{ method: "POST",	'content-type': "application/x-www-form-urlencoded", name: 'create-user', relative_url: "/user/?username=john" body: "password=admin"},
	]
});

JQuery XHR示例

$.ajax({
	method: "POST",
	dataType: "json",
	data: {
		batch: [
			{ method: "GET",	relative_url: "/product/1234" },
			{ method: "GET",	relative_url: "/users/?ids=larry,jill,sally" },
			{ method: "POST",	'content-type': "application/x-www-form-urlencoded", name: 'create-user', relative_url: "/user/?username=john" body: "password=admin" },
		]
	}
})

对于上面的示例,预期的响应格式将是

[
	{
		code: 200,
		body: { product_id: 1234 }
	},
	{
		code: 200,
		body: [{ username: "larry" }, { username: "jill" }, { username: "sally" }]
	},
	{
		code: 200,
		body: { username: "john" }
	},
]

错误

如果批处理中的某个特定请求失败,其响应将在响应数组中包含非200代码。但是,处理批处理的实际HTTP请求仍将返回200-OK。

使用JSONP指定依赖关系

有时批处理中某个请求的操作依赖于另一个请求的响应。这种依赖关系可以通过为请求指定一个名称然后使用JSONP语法访问该请求的响应来创建。

以下示例检索用户书籍集合,其中书籍表示为book_id。然后,使用批处理中的第二个请求通过这些书籍ID检索有关这些书籍的信息。

HTTP POST示例

POST /batch HTTP/1.1
Content-Type: application/json
batch: [
	{ "method": "GET", "name": "get-user-books", "relative_url": "/user_books/?username=larry" },
	{ "method": "GET", "relative_url": "/book/?book_ids={result=get-user-books:$.book_id}" },

在上面的示例中,批处理中的第一个请求被命名为get-user-books,第二个请求通过名称引用该请求并使用JSONP语法提取第一个请求中的所有book_ids,以确定要检索哪些书籍。

JSONP表达式的结果是导出为csv格式。在上面的示例中,这可能看起来像:1234,5678,9012

如果一个请求是另一个请求的依赖项并且失败,这将导致依赖该请求的请求也会失败。在上面的例子中,如果 get-user-books 请求失败,获取书籍的请求也会失败。

头部信息、Cookies 和文件

/batch/ 的 HTTP 请求相关的头部信息、cookies 和文件将对批处理中的所有请求可用。例如:将 bearer-token 身份验证作为头部信息发送,将在批处理中的所有子请求上设置该头部信息,这意味着任何身份验证中间件将针对批处理中的每个请求执行。