Skip to content

Commit

Permalink
Update supabase connection using postgres and supabas authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
manelgavalda committed Jan 11, 2024
1 parent 8b8919b commit e5e5b2d
Show file tree
Hide file tree
Showing 12 changed files with 120 additions and 104 deletions.
6 changes: 0 additions & 6 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,6 @@ VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

SUPABASE_URL=
SUPABASE_API_KEY=

ADMIN_EMAIL=
ADMIN_PASSWORD=

ASSETS_URL=

WISE_API_TOKEN=
Expand Down
11 changes: 1 addition & 10 deletions app/Http/Controllers/Auth/AuthenticatedSessionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
Expand All @@ -26,15 +25,7 @@ public function create(): View
*/
public function store(LoginRequest $request): RedirectResponse
{
$credentials = config('credentials');

if($request->email == $credentials['email'] && $request->password == $credentials['password']) {
Auth::loginUsingId(1);
} else {
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
$request->authenticate();

$request->session()->regenerate();

Expand Down
2 changes: 1 addition & 1 deletion app/Http/Controllers/Dashboard.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
class Dashboard extends Controller
{
public function __invoke() {
$supabaseService = new SupabaseService;
$wiseService = new WiseService(config('wise.api_token'), config('wise.profile_id'));
$supabaseService = (new SupabaseService(config('supabase.api_key'), config('supabase.url')));

return Inertia::render('Dashboard', [
'balance' => $wiseService->getBalance(),
Expand Down
42 changes: 0 additions & 42 deletions app/Livewire/Tokens.php

This file was deleted.

10 changes: 10 additions & 0 deletions app/Models/Balance.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Balance extends Model
{
protected $guarded = [];
}
10 changes: 10 additions & 0 deletions app/Models/Total.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Total extends Model
{
protected $guarded = [];
}
33 changes: 17 additions & 16 deletions app/Services/SupabaseService.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,39 @@
namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use App\Models\Total;
use App\Models\Balance;

class SupabaseService
{
function __construct(
protected $apiKey,
protected $url
) {}

public function getTokens()
{
return $this->getResult('balances?select=pool,price,price_eur,balance,parent,created_at&limit=450')
->sortBy('pool')->groupBy('created_at')->take(30);
return Balance::orderByDesc('created_at')->limit(450)->get()->map(function ($balance) {
$balance->price = floatval($balance->price);
$balance->balance = floatval($balance->balance);
$balance->price_eur = floatval($balance->price_eur);

return $balance;
})->sortBy('pool')->groupBy('created_at')->take(30);
}

public function getHistoricalBalances()
{
$balances = $this->getResult('totals?select=price,price_eur,balance,created_at&limit=31')
->reverse()->values();
$balances = Total::orderByDesc('created_at')->limit(31)->get()->map(function ($total) {
$total->price = floatval($total->price);
$total->balance = floatval($total->balance);
$total->price_eur = floatval($total->price_eur);

return $total;
})->reverse()->values();

return [
'prices' => $balances->pluck('price')->toArray(),
'ethereum' => $balances->pluck('balance')->toArray(),
'prices_eur' => $balances->pluck('price_eur')->toArray(),
'totals' => $balances->map(fn ($balance) => $balance->price * $balance->balance)->toArray(),
'totals_eur' => $balances->map(fn ($balance) => $balance->price_eur * $balance->balance)->toArray(),
'dates' => $balances->map(fn ($balance) => Carbon::parse($balance->created_at)->format('M d'))->toArray()
'dates' => $balances->map(fn ($balance) => Carbon::parse($balance->created_at)->format('M d Y'))->toArray()
];
}

protected function getResult($uri)
{
return collect(Http::withHeaders(['apikey' => $this->apiKey])->get("{$this->url}/rest/v1/{$uri}&order=created_at.desc")->object());
}
}
6 changes: 0 additions & 6 deletions config/credentials.php

This file was deleted.

6 changes: 0 additions & 6 deletions config/supabase.php

This file was deleted.

30 changes: 30 additions & 0 deletions database/migrations/2024_01_11_120158_create_totals_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('totals', function (Blueprint $table) {
$table->id();
$table->float('balance');
$table->float('price');
$table->float('price_eur');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('totals');
}
};
32 changes: 32 additions & 0 deletions database/migrations/2024_01_11_120203_create_balances_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('balances', function (Blueprint $table) {
$table->id();
$table->string('pool');
$table->float('balance');
$table->float('price');
$table->float('price_eur');
$table->string('parent')->nullable();
$table->timestamps();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('balances');
}
};
36 changes: 19 additions & 17 deletions tests/Unit/SupabaseServiceTest.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<?php

use Carbon\Carbon;
use App\Models\Total;
use App\Models\Balance;
use App\Services\SupabaseService;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\File;
use Illuminate\Foundation\Testing\DatabaseMigrations;

uses()->group('supabase');
uses(DatabaseMigrations::class)->group('supabase');

expect()->extend('toBeParsed', function () {
expect(reset($this->value))->toBe($this->value[0]);
Expand All @@ -14,17 +16,15 @@
});

beforeEach(function () {
$this->databaseService = new SupabaseService('fake-api-key', 'https://fake-url.supabase.co');
$this->databaseService = new SupabaseService;

fakeRequest('https://fake-url.supabase.co/rest/v1/totals?select=price,price_eur,balance,created_at&limit=31&order=created_at.desc', 'totals');
$totals = collect(json_decode(File::get(base_path() . "/tests/responses/totals.json")));

$totals->each(fn($total) => Total::create(json_decode(json_encode($total), true)));

$this->balances = $this->databaseService->getHistoricalBalances();
});

afterEach(fn () => Http::assertSent(fn (Request $request) =>
$request->hasHeader('apikey', 'fake-api-key')
));

it('retrieves_the_historical_balances', function () {
expect($dates = $this->balances['dates'])->toBeParsed();
expect($totals = $this->balances['totals'])->toBeParsed();
Expand All @@ -36,14 +36,14 @@
expect(end($totals))->toBe(end($ethereum) * end($prices));
expect(end($totalsEur))->toBe(end($ethereum) * end($pricesEur));

$lastDate = Carbon::createFromFormat('M d', end($dates));

expect(Carbon::parse($dates[0])->lt($lastDate))->toBetrue();
expect(end($dates))->toStartWith($lastDate->shortMonthName)->toEndWith($lastDate->day);
expect(end($dates))->toBe('Nov 08 2023');
expect(Carbon::parse($dates[0])->lt(Carbon::createFromFormat('M d Y', end($dates))))->toBetrue();
});

it('retrieves_the_tokens', function () {
fakeRequest('https://fake-url.supabase.co/rest/v1/balances?select=pool,price,price_eur,balance,parent,created_at&limit=450&order=created_at.desc', 'tokens');
$tokens = collect(json_decode(File::get(base_path() . "/tests/responses/tokens.json")));

$tokens->each(fn($token) => Balance::create(json_decode(json_encode($token), true)));

$tokens = $this->databaseService->getTokens();

Expand All @@ -52,7 +52,9 @@
expect($tokens)->toHaveCount(30);
expect($weeklyTokens->first())->toHaveCount(15);
expect($weeklyTokens->last())->toHaveCount(15);
expect($tokens->first()->first())->toHaveProperties(['pool', 'price', 'price_eur', 'balance', 'parent', 'created_at']);
expect(Carbon::parse($tokens->first()->first()->created_at)->isSameDay(Carbon::parse(end($this->balances['dates']))))->toBeTrue();
expect(Carbon::parse($tokens->values()->get(1)->last()->created_at)->isSameDay(Carbon::parse(prev($this->balances['dates']))))->toBeTrue();

expect($tokens->first()->first()->toArray())->toHaveKeys(['id', 'pool', 'price', 'price_eur', 'balance', 'parent', 'created_at', 'updated_at']);

expect($tokens->first()->first()->created_at->isSameDay(Carbon::parse(end($this->balances['dates']))))->toBeTrue();
expect($tokens->values()->get(1)->last()->created_at->isSameDay(Carbon::parse(prev($this->balances['dates']))))->toBeTrue();
});

0 comments on commit e5e5b2d

Please sign in to comment.