Dokumentasi

Semua yang Anda butuhkan untuk membangun aplikasi luar biasa dengan EreactThohir

Advanced Features

AI Ecosystem

AI Ecosystem

EreactThohir 1.5.0 introduces a powerful, driver-based AI ecosystem that allows you to integrate intelligence into your applications with ease.

Supported Drivers

  • OpenAI: Industry-standard models like GPT-4o.
  • Google Gemini: High-performance multimodal models.
  • Ollama: Run your own LLMs locally for maximum privacy.

Basic Usage

import { AI } from '@ereactthohir/ai';

// Simple text generation
const response = await AI.prompt('Explain quantum computing like I am five.');
console.log(response.text);

// Using a specific driver
const gemini = AI.driver('gemini');
const result = await gemini.prompt('Write a poem about TypeScript.');

Creating Custom Drivers

You can generate a new AI driver using the CLI:

ereact make:ai-driver MistralDriver
Advanced Features Updated 1 bulan yang lalu
Laporkan Masalah

Payment Gateway

Payment Gateway

Seamlessly process payments using our unified Payment Hub. Supports multiple providers out of the box.

Supported Providers

  • Midtrans: Primary Indonesian payment gateway.
  • Stripe: Global payment infrastructure.
  • Duitku & Durianpay: Localized payment solutions.

Basic Usage

import { Payment } from '@ereactthohir/payment';

const charge = await Payment.charge({
    amount: 50000,
    order_id: 'ORD-12345',
    customer: {
        name: 'John Doe',
        email: 'john@example.com'
    }
});

// Redirect to payment page
return res.redirect(charge.redirect_url);

Integration CLI

ereact make:payment-provider MyCustomProvider
Advanced Features Updated 1 bulan yang lalu
Laporkan Masalah

Enterprise CRUD

Enterprise CRUD Generator

The make:crud command is a game-changer for enterprise productivity. It generates all the boilerplates you need for a fully functional module.

What is Generated?

  • Model: Sawit ORM model with timestamps.
  • Migration: Database schema file.
  • Controller: Resource controller with CRUD methods.
  • React Page: A professional React UI page built with Rice UI.
  • Factory: Database factory for testing.

Usage

ereact make:crud Order

This single command will create:

  • app/Models/Order.ts
  • database/migrations/xxxx_create_orders_table.ts
  • app/Controllers/OrderController.ts
  • resources/js/Pages/Order/Index.tsx
  • database/factories/OrderFactory.ts
Advanced Features Updated 1 bulan yang lalu
Laporkan Masalah

Konsep Inti

Perutean

Routing

EreactThohir uses Laravel-inspired routing with TypeScript.

Basic Routes

// routes/web.ts
import { Route } from '@ereactthohir/core';

Route.get('/', (req, res) => {
    return res.view('Welcome');
});

Route.get('/about', (req, res) => {
    return res.view('About');
});

Route Parameters

Route.get('/user/:id', (req, res) => {
    const userId = req.param('id');
    return res.json({ userId });
});

Route Groups

Route.group({ prefix: '/api' }, () => {
    Route.get('/users', [UserController, 'index']);
    Route.post('/users', [UserController, 'store']);
});

Named Routes

Route.get('/dashboard', (req, res) => {
    return res.view('Dashboard');
}).name('dashboard');

// Redirect to named route
return res.redirect(route('dashboard'));

Middleware

Route.middleware(['auth']).group(() => {
    Route.get('/profile', [ProfileController, 'show']);
});
Konsep Inti Updated 1 bulan yang lalu
Laporkan Masalah

Kontroler

Controllers

Organize request handling logic into reusable classes.

Creating Controllers

Using CLI

ereact make:controller UserController

Basic Controller

import { Controller, Request, Response } from '@ereactthohir/core';

export class UserController extends Controller {
    public async index(req: Request, res: Response) {
        const users = await User.all();
        return res.json(users);
    }
    
    public async show(req: Request, res: Response) {
        const user = await User.find(req.params.id);
        return res.json(user);
    }
}

Resource Controllers

Full CRUD operations:

ereact make:controller UserController --resource

Generated methods:

  • index() - List all resources
  • create() - Show create form
  • store() - Store new resource
  • show() - Display single resource
  • edit() - Show edit form
  • update() - Update resource
  • destroy() - Delete resource

Request Validation

Validate incoming requests:

import { validate } from '@ereactthohir/core';

export class UserController extends Controller {
    public async store(req: Request, res: Response) {
        const data = await validate(req, {
            name: 'required|string|max:255',
            email: 'required|email|unique:users',
            password: 'required|min:8|confirmed'
        });
        
        const user = await User.create(data);
        return res.json(user);
    }
}

Response Types

JSON Response

return res.json({ success: true, data: users });

View Response

return res.view('users.index', { users });

Redirect Response

return res.redirect('/dashboard');

Best Practices

  1. Keep controllers thin: Move logic to services
  2. Single responsibility: One controller per resource
  3. Use type hints: Leverage TypeScript types
  4. Validate early: Validate at controller entry
  5. Return consistent responses: Use standard formats
Konsep Inti Updated 1 bulan yang lalu
Laporkan Masalah

React Components

React Components

Build UI with React components in resources/views/.

Creating Components

// resources/views/Dashboard.tsx
import React from 'react';

export default function Dashboard() {
    return (
        <div className="rice-container rice-py-8">
            <h1 className="rice-text-4xl rice-font-bold">
                Dashboard
            </h1>
        </div>
    );
}

Using Rice UI

import React from 'react';
import { Button, Card } from '@ereactthohir/rice-ui';

export default function Profile() {
    return (
        <Card className="rice-p-6">
            <h2>User Profile</h2>
            <Button variant="primary">
                Edit Profile
            </Button>
        </Card>
    );
}

Data Fetching

import React, { useEffect, useState } from 'react';

export default function Users() {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetch('/api/users')
            .then(res => res.json())
            .then(data => setUsers(data));
    }, []);

    return (
        <div>
            {users.map(user => (
                <div key={user.id}>{user.name}</div>
            ))}
        </div>
    );
}
Konsep Inti Updated 1 bulan yang lalu
Laporkan Masalah

Sawit ORM

Sawit ORM

Eloquent-like ORM for TypeScript.

Defining Models

// app/Models/User.ts
import { Model } from '@ereactthohir/core';

export class User extends Model {
    protected table = 'users';
    protected fillable = ['name', 'email', 'password'];
    protected hidden = ['password'];
}

Querying Data

// Get all users
const users = await User.all();

// Find by ID
const user = await User.find(1);

// Where clause
const admins = await User.where('role', 'admin').get();

// Pagination
const users = await User.paginate(15);

Creating Records

const user = await User.create({
    name: 'John Doe',
    email: 'john@example.com',
    password: 'hashed_password'
});

Updating Records

const user = await User.find(1);
await user.update({
    name: 'Jane Doe'
});

Deleting Records

const user = await User.find(1);
await user.delete();

Relationships

export class User extends Model {
    posts() {
        return this.hasMany(Post);
    }
}

// Usage
const user = await User.with('posts').find(1);
Konsep Inti Updated 1 bulan yang lalu
Laporkan Masalah

Middleware

Middleware

Filter permintaan HTTP yang masuk ke aplikasi Anda.

Pengenalan

Middleware menyediakan mekanisme yang nyaman untuk memeriksa dan memfilter permintaan HTTP. Kasus penggunaan umum termasuk autentikasi, logging, CORS, dan pembatasan laju.

Membuat Middleware

Menggunakan CLI

ereact make:middleware AuthMiddleware

Middleware Dasar

import { Middleware, Request, Response, NextFunction } from '@ereactthohir/core';

export class AuthMiddleware extends Middleware {
    public async handle(req: Request, res: Response, next: NextFunction) {
        if (!req.user) {
            return res.status(401).json({ error: 'Tidak terautentikasi' });
        }
        
        return next();
    }
}

Menggunakan Middleware

Pada Rute

Route.get('/dashboard', [DashboardController, 'index'])
    .middleware('auth');

// Beberapa middleware
Route.get('/admin', [AdminController, 'index'])
    .middleware(['auth', 'admin']);

Pada Kontroler

export class DashboardController extends Controller {
    constructor() {
        super();
        this.middleware('auth');
        this.middleware('admin').only(['destroy']);
        this.middleware('verified').except(['index']);
    }
}

Pada Grup Rute

Route.middleware(['auth']).group(() => {
    Route.get('/dashboard', [DashboardController, 'index']);
    Route.get('/profile', [ProfileController, 'show']);
});

Contoh Middleware Umum

Middleware Autentikasi

export class AuthMiddleware extends Middleware {
    public async handle(req: Request, res: Response, next: NextFunction) {
        const token = req.header('Authorization')?.replace('Bearer ', '');
        
        if (!token) {
            return res.status(401).json({ error: 'Token tidak disediakan' });
        }
        
        try {
            const decoded = jwt.verify(token, process.env.JWT_SECRET);
            req.user = await User.find(decoded.id);
            return next();
        } catch (error) {
            return res.status(401).json({ error: 'Token tidak valid' });
        }
    }
}

Middleware CORS

export class CorsMiddleware extends Middleware {
    public async handle(req: Request, res: Response, next: NextFunction) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
        res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        
        if (req.method === 'OPTIONS') {
            return res.status(200).end();
        }
        
        return next();
    }
}

Middleware Logging

export class LoggingMiddleware extends Middleware {
    public async handle(req: Request, res: Response, next: NextFunction) {
        const start = Date.now();
        
        // Log permintaan
        console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
        
        // Lanjutkan ke middleware berikutnya
        const result = await next();
        
        // Log waktu respons
        const duration = Date.now() - start;
        console.log(`[${new Date().toISOString()}] Selesai dalam ${duration}ms`);
        
        return result;
    }
}

Praktik Terbaik

  1. Jaga middleware tetap fokus: Satu tanggung jawab per middleware
  2. Urutan itu penting: Daftarkan middleware dalam urutan yang benar
  3. Performa: Hindari operasi berat di middleware global
  4. Penanganan kesalahan: Selalu tangani kesalahan dengan anggun
  5. Pengujian: Tulis pengujian untuk logika middleware
Konsep Inti Updated 1 bulan yang lalu
Laporkan Masalah

Basis Data

Migrasi

Database Migrations

Manage database schema with TypeScript migrations.

Creating Migrations

ereact make:migration create_users_table

Migration Structure

// database/migrations/2024_01_01_create_users_table.ts
import { Migration, Schema } from '@ereactthohir/core';

export default class CreateUsersTable extends Migration {
    async up() {
        await Schema.create('users', (table) => {
            table.id();
            table.string('name');
            table.string('email').unique();
            table.string('password');
            table.timestamps();
        });
    }

    async down() {
        await Schema.drop('users');
    }
}

Running Migrations

# Run all pending migrations
ereact migrate

# Rollback last batch
ereact migrate:rollback

# Reset database
ereact migrate:fresh

Column Types

table.id();                    // Auto-increment ID
table.string('name');          // VARCHAR
table.text('description');     // TEXT
table.integer('age');          // INTEGER
table.boolean('is_active');    // BOOLEAN
table.timestamp('created_at'); // TIMESTAMP
table.timestamps();            // created_at & updated_at
Basis Data Updated 1 bulan yang lalu
Laporkan Masalah

Frontend

Komponen Rice UI

Rice UI Components

Beautiful, accessible React components.

Button

import { Button } from '@ereactthohir/rice-ui';

<Button variant="primary">Click Me</Button>
<Button variant="secondary">Secondary</Button>
<Button variant="danger">Delete</Button>

Input

import { Input } from '@ereactthohir/rice-ui';

<Input 
    type="email"
    placeholder="Enter email"
    value={email}
    onChange={(e) => setEmail(e.target.value)}
/>

Card

import { Card } from '@ereactthohir/rice-ui';

<Card className="rice-p-6">
    <h3>Card Title</h3>
    <p>Card content goes here</p>
</Card>

Modal

import { Modal } from '@ereactthohir/rice-ui';

<Modal isOpen={isOpen} onClose={() => setIsOpen(false)}>
    <h2>Modal Title</h2>
    <p>Modal content</p>
</Modal>

Table

import { Table } from '@ereactthohir/rice-ui';

<Table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        {users.map(user => (
            <tr key={user.id}>
                <td>{user.name}</td>
                <td>{user.email}</td>
            </tr>
        ))}
    </tbody>
</Table>
Frontend Updated 1 bulan yang lalu
Laporkan Masalah

Mulai Sekarang

Pengenalan

Introduction to EreactThohir

EreactThohir is a modern fullstack framework that combines React's component-based architecture with Laravel-inspired backend patterns, all written in TypeScript.

What is EreactThohir?

EreactThohir brings the best of both worlds:

  • React 18+ for building interactive UIs
  • TypeScript for type safety
  • Sawit ORM - Eloquent-like database abstraction
  • Rice UI - Beautiful component library
  • MVC Architecture - Clean separation of concerns

Core Features

🎯 Type-Safe Development

Full TypeScript support from database to UI components.

âš¡ Performance First

Optimized SSR, code splitting, and lazy loading out of the box.

🎨 Rice UI Components

Pre-built, accessible components with modern design.

📱 Mobile & Web

Build for web, mobile (iOS/Android), or both from one codebase.

Quick Example

import { Route } from '@ereactthohir/core';

Route.get('/', (req, res) => {
    return res.view('Welcome');
});
// resources/views/Welcome.tsx
import React from 'react';

export default function Welcome() {
    return (
        <div className="rice-container">
            <h1>Welcome to EreactThohir!</h1>
        </div>
    );
}
Mulai Sekarang Updated 1 bulan yang lalu
Laporkan Masalah

Instalasi

Installation

Prerequisites

  • Node.js 18.x or higher
  • npm or yarn
  • Git (recommended)

Quick Start

Using CLI (Recommended)

# Install CLI globally
npm install -g @ereactthohir/cli

# Create new project
ereact create my-app

# Navigate and run
cd my-app
npm install
ereact jalan

Manual Setup

# Clone starter template
git clone https://github.com/ereactthohir/starter.git my-app
cd my-app

# Install dependencies
npm install

# Run development server
npm run dev

Project Structure

my-app/
├── app/
│   ├── Controllers/
│   ├── Models/
│   ├── Middleware/
│   └── Services/
├── resources/
│   ├── views/          # React components
│   └── rice-ui/        # UI components
├── routes/
│   ├── web.ts
│   ├── api.ts
│   └── mobile.ts
├── database/
│   ├── migrations/
│   └── seeders/
└── ereactthohir.config.ts

Configuration

Edit ereactthohir.config.ts:

export default {
    name: 'MyApp',
    env: 'local',
    database: {
        driver: 'sawit',
        connection: 'default'
    }
};

Environment Variables

Create .env file:

APP_NAME=MyApp
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost

DB_DRIVER=sawit
DB_CONNECTION=default
Mulai Sekarang Updated 1 bulan yang lalu
Laporkan Masalah

Struktur Proyek

Project Structure

Understanding the EreactThohir project structure.

Directory Overview

my-app/
├── app/
│   ├── Controllers/      # HTTP Controllers (.ts)
│   ├── Models/          # Database Models (.ts)
│   ├── Services/        # Business Logic (.ts)
│   └── Middleware/      # HTTP Middleware (.ts)
├── config/              # Configuration files
├── database/
│   ├── migrations/      # Database migrations (.ts)
│   └── seeders/         # Database seeders (.ts)
├── public/              # Public assets
├── resources/
│   ├── views/           # React components / templates
│   ├── js/              # Frontend TypeScript
│   └── css/             # Stylesheets
├── routes/
│   ├── web.ts           # Web routes
│   └── api.ts           # API routes
├── storage/             # File storage
├── tests/               # Test files
└── node_modules/        # Dependencies

Key Directories

/app

Contains your application's core logic:

  • Controllers: Handle HTTP requests
  • Models: Database models using Sawit ORM
  • Services: Reusable business logic
  • Middleware: Request/response filters

/config

Configuration files for:

  • Database connections
  • Cache settings
  • Queue configurations
  • Application settings

/resources

Frontend and view files:

  • views: Blade templates
  • js: TypeScript/JavaScript files
  • css: Stylesheets

/routes

Route definitions:

  • web.php: Web routes with session
  • api.php: API routes (stateless)

File Naming Conventions

  • Controllers: PascalCase + Controller suffix
    • Example: UserController.ts
  • Models: PascalCase singular
    • Example: User.ts
  • Services: PascalCase + Service suffix
    • Example: AuthService.ts
  • Views: PascalCase components
    • Example: UserProfile.tsx

Best Practices

  1. Keep controllers thin: Move business logic to services
  2. Use models for data: Never write raw SQL in controllers
  3. Organize by feature: Group related files together
  4. Follow TypeScript standards: Consistent code style

Next Steps

  • Routing
  • Controllers
  • Models
Mulai Sekarang Updated 1 bulan yang lalu
Laporkan Masalah

Konfigurasi

Konfigurasi

Pelajari cara mengonfigurasi aplikasi EreactThohir Anda.

Konfigurasi Lingkungan

Semua konfigurasi spesifik lingkungan disimpan dalam file .env.

Membuat File .env

cp .env.example .env
ereact key:generate

Opsi Konfigurasi Utama

Pengaturan Aplikasi

APP_NAME="Aplikasi Saya"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost:8000
APP_TIMEZONE=Asia/Jakarta

Konfigurasi Database

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ereact_db
DB_USERNAME=root
DB_PASSWORD=secret

Mengakses Konfigurasi

Di TypeScript

import { config } from '@ereactthohir/core';

const apiUrl = config('app.url');

// Ambil dengan default
const driver = config('cache.driver', 'file');

// Catatan: Konfigurasi harus dikelola melalui file .env

Praktik Terbaik

  1. Jangan pernah commit .env: Jaga keamanan data sensitif
  2. Gunakan .env.example: Dokumentasikan variabel yang diperlukan
  3. Validasi konfigurasi: Periksa nilai yang diperlukan saat boot
  4. Cache konfigurasi: Konfigurasi secara otomatis dimuat saat boot
Mulai Sekarang Updated 1 bulan yang lalu
Laporkan Masalah

Keamanan

Autentikasi

Authentication

Built-in authentication with Semouth.

Installation

# During project creation
ereact create my-app
# Select "Install Semouth" when prompted

# Or install later
ereact semouth:install

Login Controller

// app/Controllers/Auth/LoginController.ts
import { Controller } from '@ereactthohir/core';

export class LoginController extends Controller {
    async store(req, res) {
        const { email, password } = req.only('email', 'password');
        
        const user = await req.app.make('auth')
            .attempt(email, password);
        
        req.session.set('user_id', user.id);
        return res.redirect('/');
    }
}

Login Component

// resources/views/auth/Login.tsx
import React, { useState } from 'react';
import { Button, Input } from '@ereactthohir/rice-ui';

export default function Login() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        await fetch('/auth/login', {
            method: 'POST',
            body: JSON.stringify({ email, password })
        });
    };

    return (
        <form onSubmit={handleSubmit}>
            <Input 
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
            />
            <Input 
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
            />
            <Button type="submit">Login</Button>
        </form>
    );
}

Protected Routes

Route.middleware(['auth']).group(() => {
    Route.get('/dashboard', [DashboardController, 'index']);
});
Keamanan Updated 1 bulan yang lalu
Laporkan Masalah

Butuh Bantuan?

Tidak dapat menemukan apa yang Anda cari? Kami siap membantu.