Ver Fonte

:sparkles: create discusson

visuddhinanda há 3 anos atrás
pai
commit
9f7fb9a323

+ 147 - 0
app/Http/Controllers/DiscussionController.php

@@ -0,0 +1,147 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Models\Discussion;
+use Illuminate\Http\Request;
+use App\Http\Resources\DiscussionResource;
+
+
+class DiscussionController extends Controller
+{
+    /**
+     * Display a listing of the resource.
+     *
+     * @return \Illuminate\Http\Response
+     */
+    public function index(Request $request)
+    {
+        //
+		switch ($request->get('view')) {
+            case 'res_id':
+                $table = Discussion::where('res_id',$request->get('id'));
+                break;
+            case 'parent':
+                $table = Discussion::where('parent',$request->get('id'));
+                break;
+        }
+        if(!empty($search)){
+            $table->where('title', 'like', $search."%");
+        }
+        if(!empty($request->get('order')) && !empty($request->get('dir'))){
+            $table->orderBy($request->get('order'),$request->get('dir'));
+        }else{
+            $table->orderBy('updated_at','desc');
+        }
+        $count = $table->count();
+        if(!empty($request->get('limit'))){
+            $offset = 0;
+            if(!empty($request->get("offset"))){
+                $offset = $request->get("offset");
+            }
+            $table->skip($offset)->take($request->get('limit'));
+        }
+        $result = $table->get();
+        if($result){
+			return $this->ok(["rows"=>DiscussionResource::collection($result),"count"=>$count]);
+		}else{
+			return $this->error("没有查询到数据");
+		}
+    }
+
+    /**
+     * Store a newly created resource in storage.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return \Illuminate\Http\Response
+     */
+    public function store(Request $request)
+    {
+        $user = \App\Http\Api\AuthApi::current($request);
+        if(!$user){
+            return $this->error(__('auth.failed'));
+        }
+        //
+        // validate
+        // read more on validation at http://laravel.com/docs/validation
+        $rules = array(
+            'res_id' => 'required',
+            'res_type' => 'required',
+        );
+        if(!$request->has('parent')){
+            $rules['title'] = 'required';
+        }
+
+        $validated = $request->validate($rules);
+
+        $discussion = new Discussion;
+        $discussion->res_id = $request->get('res_id');
+        $discussion->res_type = $request->get('res_type');
+        $discussion->title = $request->get('title',null);
+        $discussion->content = $request->get('content',null);
+        $discussion->parent = $request->get('parent',null);
+        $discussion->editor_uid = $user['user_uid'];
+        $discussion->save();
+        return $this->ok(new DiscussionResource($discussion));
+    }
+
+    /**
+     * Display the specified resource.
+     *
+     * @param  \App\Models\Discussion  $discussion
+     * @return \Illuminate\Http\Response
+     */
+    public function show(Discussion $discussion)
+    {
+        //
+        return $this->ok(new DiscussionResource($discussion));
+
+    }
+
+    /**
+     * Update the specified resource in storage.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \App\Models\Discussion  $discussion
+     * @return \Illuminate\Http\Response
+     */
+    public function update(Request $request, Discussion $discussion)
+    {
+        //
+        $user = \App\Http\Api\AuthApi::current($request);
+        if(!$user){
+            return $this->error(__('auth.failed'));
+        }
+        //
+        if($discussion->editor !== $user['user_uid']){
+            return $this->error(__('auth.failed'));
+        }
+        $discussion->title = $request->get('title',null);
+        $discussion->content = $request->get('content',null);
+        $discussion->editor_uid = $user['user_uid'];
+        $discussion->save();
+        return $this->ok($discussion);
+
+    }
+
+    /**
+     * Remove the specified resource from storage.
+     *
+     * @param  \App\Models\Discussion  $discussion
+     * @return \Illuminate\Http\Response
+     */
+    public function destroy(Discussion $discussion)
+    {
+        //
+        $user = \App\Http\Api\AuthApi::current($request);
+        if(!$user){
+            return $this->error(__('auth.failed'));
+        }
+        //TODO 其他有权限的人也可以删除
+        if($discussion->editor !== $user['user_uid']){
+            return $this->error(__('auth.failed'));
+        }
+        $delete = $discussion->delete();
+        return $this->ok($delete);
+    }
+}

+ 34 - 0
app/Http/Resources/DiscussionResource.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Http\Resources;
+use App\Http\Api\StudioApi;
+use App\Http\Api\AuthApi;
+
+use Illuminate\Http\Resources\Json\JsonResource;
+
+class DiscussionResource extends JsonResource
+{
+    /**
+     * Transform the resource into an array.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
+     */
+    public function toArray($request)
+    {
+        //获取用户信息
+        $user = AuthApi::current($request);
+
+        return [
+            "id"=>$this->id,
+            "title"=> $this->title,
+            "content"=> $this->content,
+            "parent"=> $this->parent,
+            "editor"=> StudioApi::getById($this->editor_uid),
+            "res_id"=>$this->res_id,
+            "res_type"=> $this->res_type,
+            "created_at"=> $this->created_at,
+            "updated_at"=> $this->updated_at,
+        ];
+    }
+}

+ 15 - 0
app/Models/Discussion.php

@@ -0,0 +1,15 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+class Discussion extends Model
+{
+    use HasFactory;
+    protected $primaryKey = 'id';
+	protected $casts = [
+		'id' => 'string'
+	];
+}

+ 39 - 0
database/migrations/2022_12_19_125601_create_discussions_table.php

@@ -0,0 +1,39 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+class CreateDiscussionsTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::create('discussions', function (Blueprint $table) {
+            $table->uuid('id')->primary()->default(DB::raw('uuid_generate_v1mc()'));
+			$table->uuid('res_id')->index();
+			$table->string('res_type',32)->index();
+			$table->uuid('parent')->index()->nullable();
+			$table->string('title',256)->nullable();
+			$table->text('content')->nullable();
+            $table->integer('children_count')->default(0);
+			$table->uuid('editor_uid')->index();
+			$table->string('publicity',32)->default('public');
+            $table->timestamps();
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::dropIfExists('discussions');
+    }
+}

+ 56 - 0
tests/Feature/DiscussionTest.php

@@ -0,0 +1,56 @@
+<?php
+
+namespace Tests\Feature;
+
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Foundation\Testing\WithFaker;
+use Tests\TestCase;
+use Illuminate\Support\Str;
+
+class DiscussionTest extends TestCase
+{
+    /**
+     * A basic feature test example.
+     *
+     * @return void
+     */
+    public function test_example()
+    {
+        $token = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJuYmYiOjE2NjgyMzE3MTksImV4cCI6MTY5OTc2NzcxOSwidWlkIjoiYmE1NDYzZjMtNzJkMS00NDEwLTg1OGUtZWFkZDEwODg0NzEzIiwiaWQiOiI0In0.LV4ItC5VCqXpbKIXT1zePcnfi-heCf3Df63w7qbXsT1i5KJtwJJC938CLgANjqwcQFa3lrR5TqvT1kkqD-Mmgg';
+        //testing index
+        $response = $this->get('/api/v2/discussion?view=res_id&id=eae9fd6f-7bac-4940-b80d-ad6cd6f433bf');
+
+        $response->assertStatus(200);
+
+        //testing store
+        $response = $this->withHeaders([
+            'Authorization' => $token,
+        ])->json('POST', '/api/v2/discussion',
+                    [
+                        'title'=>'test',
+                        'res_id'=>'eae9fd6f-7bac-4940-b80d-ad6cd6f433bf',
+                        'res_type'=>'wbw',
+                    ]);
+
+        $response->assertOk();
+
+        $id = $response['data']['id'];
+        $this->assertTrue(Str::isUuid($id));
+
+        //testing answer
+        $response = $this->withHeaders([
+            'Authorization' => $token,
+        ])->json('POST', '/api/v2/discussion',
+                    [
+                        'parent' => $id,
+                        'content'=>'answer',
+                        'res_id'=>'eae9fd6f-7bac-4940-b80d-ad6cd6f433bf',
+                        'res_type'=>'wbw',
+                    ]);
+
+        $response->assertOk();
+
+        $id = $response['data']['id'];
+        $this->assertTrue(Str::isUuid($id));
+    }
+}