shalvah/laravel-jsend

Laravel 辅助函数,轻松发送符合 JSend 标准的响应

2.4 2023-04-07 10:57 UTC

This package is auto-updated.

Last update: 2024-09-07 14:02:00 UTC


README

Latest Stable Version Total Downloads

简单的辅助函数,用于为您的 Laravel 应用生成符合 JSend 标准的响应

JSend 规范规定了 Web 服务器返回的 JSON 响应应该如何格式化。JSend 特别适合 REST 风格的应用程序和 API。

安装

Laravel 7 及以上版本

composer require shalvah/laravel-jsend

Laravel 5.1 - 6.*

composer require shalvah/laravel-jsend:^1.0

使用方法

在控制器中

public function create(Request $request)
{
  $userData = $request->input('data');
  if (empty($userData['email']))
      return jsend_fail(['email' => 'Email is required']);
  
  try {
      $user = User::create($userData):
      return jsend_success($user);
  } catch (Exception $e) {
      return jsend_error('Unable to create user: '.$e->getMessage());
  }
}

您还可以在 App\Exceptions\Handler 中添加 JsendExceptionFormatter 特性,以将未处理的异常和 Laravel 验证错误格式化为 JSend 格式

class Handler extends ExceptionHandler
{
    use Shalvah\LaravelJsend\JsendExceptionFormatter;
    
    // ...
}

可用的辅助函数

jsend_success

jsend_success 函数创建一个 JSend 成功 响应实例。

return jsend_success([
  "id" => 2,
  "title" => "New life",
  "body" => "Trust me, this is great!"
]);

生成响应

{
  "status": "success",
  "data": {
    "id": 2,
    "title": "New life",
    "body": "Trust me, this is great!"
  }
}

您可以将 Eloquent 模型作为“数据”对象传递,而不是数组

$post = Post::find($id);
return jsend_success($post);

jsend_fail

jsend_fail 函数创建一个 JSend 失败 响应实例。

return jsend_fail([
    "title" => "title is required",
    "body" => "body must be 50 - 10000 words"
]);

生成响应

{
  "status": "fail",
  "data": {
    "title": "title is required",
    "body": "body must be 50 - 10000 words"
  }
}

jsend_error

jsend_error 函数创建一个 JSend 错误 响应实例。

return jsend_error("Unable to connect to database");

生成响应

{
  "status": "error",
  "message":"Unable to connect to database"
}

您还可以传递可选的 codedata 对象。

return jsend_error("Unable to connect to database", 'E0001', ['type' => 'database error']);

生成响应

{
  "status": "error",
  "message":"Unable to connect to database",
  "code": "E001",
  "data": {
    "type": "database error"
  }
}

注意:对于每个辅助函数,HTTP 状态码都会自动设置(分别为 200、400 和 500,分别对应 successfailerror),并且会设置 Content-type: application/json 标头。如果您希望,可以指定 HTTP 状态码和额外的标头作为最后两个参数。

return jsend_success($post, 201, ["X-My-Header" => "header value"]);
return jsend_fail(["location_id" => "Location not found"], 404);
return jsend_error("Unable to connect to database", 'E0001', [], 503, ["X-My-Header" => "header value"]);

许可证

MIT