44
55use App \ApiJson \Parse \Parse ;
66use App \Constants \ResponseCode ;
7+ use App \Event \ApiJson \RequestHandleAfter ;
8+ use App \Event \ApiJson \RequestHandleBefore ;
79use Hyperf \HttpServer \Contract \RequestInterface ;
10+ use Hyperf \Utils \ApplicationContext ;
11+ use Psr \EventDispatcher \EventDispatcherInterface ;
812
913class ApiJson
1014{
@@ -14,16 +18,28 @@ public function __construct(protected RequestInterface $request, protected strin
1418
1519 public function Query (): array
1620 {
17- if (!is_array (json_decode ($ this ->request ->getBody ()->getContents (), true ))) {
18- return [
19- 'code ' => ResponseCode::CODE_UNSUPPORTED_ENCODING ,
20- 'msg ' => ResponseCode::getMessage (ResponseCode::CODE_UNSUPPORTED_ENCODING )
21- ];
21+ $ content = $ this ->request ->getBody ()->getContents ();
22+ $ beforeEvent = new RequestHandleBefore ($ content , $ this ->method );
23+ ApplicationContext::getContainer ()->get (EventDispatcherInterface::class)->dispatch ($ beforeEvent );
24+
25+ if (empty ($ beforeEvent ->response )) { //提供更多可能性, 如接入缓存功能
26+ if (!is_array (json_decode ($ beforeEvent ->content , true ))) {
27+ return [
28+ 'code ' => ResponseCode::CODE_UNSUPPORTED_ENCODING ,
29+ 'msg ' => ResponseCode::getMessage (ResponseCode::CODE_UNSUPPORTED_ENCODING )
30+ ];
31+ }
32+ $ parse = new Parse (json_decode ($ beforeEvent ->content , true ), $ this ->method , $ this ->request ->input ('tag ' , '' ));
33+ $ response = $ parse ->handle ();
34+ } else {
35+ $ response = $ beforeEvent ->response ;
2236 }
23- $ parse = new Parse (json_decode ($ this ->request ->getBody ()->getContents (), true ), $ this ->method , $ this ->request ->input ('tag ' , '' ));
37+
38+ ApplicationContext::getContainer ()->get (EventDispatcherInterface::class)->dispatch (new RequestHandleAfter ($ beforeEvent ->content , $ response ));
39+
2440 return array_merge ([
2541 'code ' => ResponseCode::CODE_SUCCESS ,
2642 'msg ' => ResponseCode::getMessage (ResponseCode::CODE_SUCCESS )
27- ], $ parse -> handle () );
43+ ], $ response );
2844 }
2945}
0 commit comments