Lae/app/Models/Module/Module.php

110 lines
2.5 KiB
PHP
Raw Normal View History

2022-08-13 06:04:47 +00:00
<?php
namespace App\Models\Module;
2022-08-19 10:14:23 +00:00
use Http;
2022-08-14 13:57:56 +00:00
use Illuminate\Support\Str;
2022-08-13 06:04:47 +00:00
use Illuminate\Database\Eloquent\Model;
2022-08-14 13:57:56 +00:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
2022-08-14 17:03:41 +00:00
use Illuminate\Foundation\Auth\User as Authenticatable;
2022-08-13 06:04:47 +00:00
2022-08-14 17:03:41 +00:00
class Module extends Authenticatable
2022-08-13 06:04:47 +00:00
{
use HasFactory;
protected $table = 'modules';
2022-08-14 13:57:56 +00:00
// primary key
public $incrementing = false;
protected $keyType = 'string';
public $timestamps = false;
2022-08-13 06:04:47 +00:00
protected $fillable = [
2022-08-14 13:57:56 +00:00
'id',
2022-08-14 14:00:22 +00:00
'name',
2022-08-14 13:57:56 +00:00
'api_token'
2022-08-13 06:04:47 +00:00
];
2022-08-14 13:57:56 +00:00
2022-08-19 10:14:23 +00:00
2022-08-19 10:31:24 +00:00
public function remoteHost($host_id, $func, $requests)
{
$http = Http::remote($this->api_token, $this->url);
$response = $http->post("hosts/{$host_id}/functions/" . $func, $requests);
$json = $response->json();
$status = $response->status();
return [$json, $status];
}
2022-08-19 10:14:23 +00:00
public function remote($func, $requests)
{
$http = Http::remote($this->api_token, $this->url);
$response = $http->post('functions/' . $func, $requests);
$json = $response->json();
$status = $response->status();
return [$json, $status];
}
2022-08-29 09:31:08 +00:00
// post, get, patch, delete 等请求
public function remoteRequest($method, $func, $requests)
{
$http = Http::remote($this->api_token, $this->url)
->accept('application/json')
->withHeaders(['X-Func' => $func]);
unset($requests['func']);
$requests['user_id'] = auth('sanctum')->id();
$user = auth('sanctum')->user();
if ($method == 'post') {
// add user to requests
$requests['user'] = $user;
}
$requests['user_id'] = $user['id'];
2022-08-29 09:31:08 +00:00
$response = $http->{$method}("functions/{$func}", $requests);
$json = $response->json();
$status = $response->status();
return [
'body' => $response->body(),
'json' => $json,
'status' => $status
];
}
2022-08-26 14:37:20 +00:00
public function remotePost($path = '', $data = [])
{
$http = Http::remote($this->api_token, $this->url);
$response = $http->post($path, $data);
$json = $response->json();
$status = $response->status();
return [$json, $status];
}
2022-08-14 13:57:56 +00:00
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
// if local
if (!app()->environment('local')) {
$model->api_token = Str::random(60);
}
});
}
2022-08-13 06:04:47 +00:00
}