Skip to content

Commit

Permalink
Restructure app config (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
necessarylion authored Dec 6, 2023
1 parent dd08d0d commit bb18bed
Show file tree
Hide file tree
Showing 35 changed files with 261 additions and 246 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,7 @@ jobs:
sdk: stable
- name: Activate melos
run: dart pub global activate melos
- name: Melos Bootstrap
run: melos bs
- name: Run Tests
run: melos test
2 changes: 1 addition & 1 deletion docs/the-basic/request.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Register a request in `lib/config/app.dart`

```dart
@override
Map<Type, Function()> get formRequests => {
Map<Type, FormRequest Function()> get formRequests => {
BlogRequest:() => BlogRequest(),
};
```
Expand Down
2 changes: 1 addition & 1 deletion packages/dox-app/.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
APP_PORT=3001
APP_PORT=3003
APP_KEY=KKep5qC6uHlAgrwaQTQewgMRSIqQnoj0

DB_HOST=localhost
Expand Down
8 changes: 1 addition & 7 deletions packages/dox-app/bin/server.dart
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import 'package:dox_app/config/app.dart';
import 'package:dox_app/services/auth_service.dart';
import 'package:dox_app/services/database_service.dart';
import 'package:dox_app/services/websocket_service.dart';
import 'package:dox_core/dox_core.dart';

void main() async {
/// Initialize Dox
Dox().initialize(Config());

Dox().addService(DatabaseService());
Dox().addService(AuthService());
Dox().addService(WebsocketService());
Dox().initialize(appConfig);

/// run database migration before starting server
await DatabaseService().migrate();
Expand Down
100 changes: 44 additions & 56 deletions packages/dox-app/lib/config/app.dart
Original file line number Diff line number Diff line change
@@ -1,63 +1,51 @@
import 'package:dox_app/config/cache.dart';
import 'package:dox_app/config/cors.dart';
import 'package:dox_app/config/services.dart';
import 'package:dox_app/config/storage.dart';
import 'package:dox_app/http/handler.dart';
import 'package:dox_app/http/requests/blog.request.dart';
import 'package:dox_app/routes/api.dart';
import 'package:dox_app/routes/web.dart';
import 'package:dox_app/routes/websocket.dart';
import 'package:dox_core/cache/drivers/file/file_cache_driver.dart';
import 'package:dox_core/dox_core.dart';

class Config extends AppConfig {
@override
int get totalIsolate => 6;

@override
String get appKey => Env.get('APP_KEY');

@override
int get serverPort => int.parse(Env.get('APP_PORT', 3000));

@override
Map<Type, Function()> get formRequests => <Type, Function()>{
BlogRequest: () => BlogRequest(),
};

@override
List<dynamic> get globalMiddleware => <dynamic>[
// LogMiddleware(filter: logFilter, withHeader: true),
];

@override
List<Router> get routers => <Router>[
WebRouter(),
ApiRouter(),
WebsocketRouter(),
];

@override
CORSConfig get cors => CORSConfig(
allowOrigin: '*',
allowHeaders: '*',
allowMethods: '*',
allowCredentials: true,
exposeHeaders: '*',
);
@override
CacheConfig get cacheConfig => CacheConfig(
drivers: <String, CacheDriverInterface>{
'file': FileCacheDriver(),
},
);

@override
ResponseHandlerInterface get responseHandler => ResponseHandler();

// @override
// void Function(Object? error, StackTrace stackTrace) get errorHandler =>
// (Object? error, StackTrace stackTrace) {
// DoxLogger.prettyLog(
// 'error',
// error.toString(),
// stackTrace.toString(),
// );
// };
}
AppConfig appConfig = AppConfig(
/// application key
appKey: Env.get('APP_KEY'),

/// application server port
serverPort: int.parse(Env.get('APP_PORT', 3000)),

/// total multi-thread isolate to run
totalIsolate: 6,

/// global middleware
globalMiddleware: <dynamic>[],

/// form requests
formRequests: <Type, FormRequest Function()>{
BlogRequest: () => BlogRequest(),
},

/// routers
routers: <Router>[
WebRouter(),
ApiRouter(),
WebsocketRouter(),
],

/// response handler
responseHandler: ResponseHandler(),

/// service to run on multithread server
services: services,

/// cors configuration
cors: cors,

/// cache driver configuration
cache: cache,

/// file storage driver configuration
fileStorage: storage,
);
12 changes: 12 additions & 0 deletions packages/dox-app/lib/config/cache.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import 'package:dox_core/cache/drivers/file/file_cache_driver.dart';
import 'package:dox_core/dox_core.dart';

CacheConfig cache = CacheConfig(
/// default cache driver
defaultDriver: Env.get('CACHE_DRIVER', 'file'),

/// register cache driver list
drivers: <String, CacheDriverInterface>{
'file': FileCacheDriver(),
},
);
3 changes: 3 additions & 0 deletions packages/dox-app/lib/config/cors.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import 'package:dox_core/dox_core.dart';

CORSConfig cors = CORSConfig();
10 changes: 10 additions & 0 deletions packages/dox-app/lib/config/services.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import 'package:dox_app/services/auth_service.dart';
import 'package:dox_app/services/database_service.dart';
import 'package:dox_app/services/websocket_service.dart';
import 'package:dox_core/dox_core.dart';

List<DoxService> services = <DoxService>[
DatabaseService(),
AuthService(),
WebsocketService(),
];
12 changes: 12 additions & 0 deletions packages/dox-app/lib/config/storage.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import 'package:dox_core/dox_core.dart';
import 'package:dox_core/storage/local_storage_driver.dart';

FileStorageConfig storage = FileStorageConfig(
/// default storage driver
defaultDriver: Env.get('STORAGE_DRIVER', 'local'),

// register storage driver list
drivers: <String, StorageDriverInterface>{
'local': LocalStorageDriver(),
},
);
6 changes: 3 additions & 3 deletions packages/dox-app/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ packages:
path: "../dox-core"
relative: true
source: path
version: "2.0.0-alpha.2"
version: "2.0.0-alpha.3"
dox_migration:
dependency: "direct main"
description:
Expand Down Expand Up @@ -286,10 +286,10 @@ packages:
dependency: transitive
description:
name: encrypt
sha256: "4fd4e4fdc21b9d7d4141823e1e6515cd94e7b8d84749504c232999fba25d9bbb"
sha256: "62d9aa4670cc2a8798bab89b39fc71b6dfbacf615de6cf5001fb39f7e4a996a2"
url: "https://pub.dev"
source: hosted
version: "5.0.1"
version: "5.0.3"
executor:
dependency: transitive
description:
Expand Down
2 changes: 1 addition & 1 deletion packages/dox-app/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ dependencies:
short_uuids: ^2.0.0
dox_auth: ^2.0.0-alpha.2
dox_migration: ^1.0.4
dox_core: ^2.0.0-alpha.2
dox_core: ^2.0.0-alpha.3
dox_websocket: ^1.0.0-beta.1
dox_query_builder: ^1.1.15

Expand Down
4 changes: 1 addition & 3 deletions packages/dox-app/test/cache_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,14 @@ import 'package:dox_app/config/app.dart';
import 'package:dox_core/dox_core.dart';
import 'package:test/test.dart';

Config config = Config();

void main() {
group('Cache |', () {
setUpAll(() async {
Directory storage = Directory('${Directory.current.path}/storage/');
if (storage.existsSync()) {
storage.deleteSync(recursive: true);
}
Dox().initialize(config);
Dox().initialize(appConfig);
});

test('put', () async {
Expand Down
5 changes: 2 additions & 3 deletions packages/dox-app/test/http_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import 'package:dox_core/dox_core.dart';
import 'package:http/http.dart' as http;
import 'package:test/test.dart';

Config config = Config();
String baseUrl = 'http://localhost:${config.serverPort}';
String baseUrl = 'http://localhost:${appConfig.serverPort}';

void main() {
setUpAll(() async {
Dox().initialize(config);
Dox().initialize(appConfig);
Dox().addService(AuthService());
Dox().addService(WebsocketService());
await Dox().startServer();
Expand Down
4 changes: 4 additions & 0 deletions packages/dox-core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# version 2.0.0-alpha.3

- Restructure app configuration

# version 2.0.0-alpha.2

- Extract websocket as separate package `dox-websocket`
Expand Down
1 change: 1 addition & 0 deletions packages/dox-core/lib/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class Dox implements IDox {
/// await Dox().startServer();
/// ```
Future<void> startServer() async {
addServices(config.services);
_totalIsolate ??= Dox().config.totalIsolate;
int isolatesToSpawn = _totalIsolate ?? 1;

Expand Down
6 changes: 3 additions & 3 deletions packages/dox-core/lib/cache/cache.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Cache {
Map<String, CacheDriverInterface> cacheDrivers =
<String, CacheDriverInterface>{
'file': FileCacheDriver(),
...Dox().config.cacheConfig.drivers,
...Dox().config.cache.drivers,
};

/// Set where to store the cache.
Expand All @@ -33,9 +33,9 @@ class Cache {

/// get the cache driver
CacheDriverInterface get _driver {
_store ??= Dox().config.cacheConfig.defaultDriver;
_store ??= Dox().config.cache.defaultDriver;
CacheDriverInterface d = cacheDrivers[_store] ??
cacheDrivers[Dox().config.cacheConfig.defaultDriver] ??
cacheDrivers[Dox().config.cache.defaultDriver] ??
FileCacheDriver();
d.setTag(_tag);
return d;
Expand Down
18 changes: 14 additions & 4 deletions packages/dox-core/lib/env/env.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,22 @@ class Env {
/// ```
/// Evn.get('APP_KEY');
/// Evn.get('APP_KEY', 'with_default_value_if_null');
/// Evn.get<int>('PORT', 3000); (This will return int type)
/// Evn.get<num>('PORT', 3000); (This will return num type)
/// Evn.get<String>('APP_KEY'); (This will return type String)
/// Current this function support String, int and num types.
/// ```
static String get(String key, [dynamic defaultValue]) {
static T get<T>(String key, [dynamic defaultValue]) {
String value = Env().env[key].toString();
return value.isEmpty || value.toLowerCase() == 'null'
? defaultValue
: value;
String val =
value.isEmpty || value.toLowerCase() == 'null' ? defaultValue : value;
if (T.toString() == 'int') {
return int.parse(val) as T;
}
if (T.toString() == 'num') {
return num.parse(val) as T;
}
return val as T;
}

/// load env from .env of project directory
Expand Down
59 changes: 33 additions & 26 deletions packages/dox-core/lib/interfaces/app_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,39 @@
import 'package:dox_core/dox_core.dart';
import 'package:dox_core/utils/logger.dart';

abstract class AppConfig {
String get appKey;

int totalIsolate = 3;

int get serverPort;

ResponseHandlerInterface get responseHandler;

void Function(Object?, StackTrace) get errorHandler =>
(Object? error, StackTrace stackTrace) {
DoxLogger.warn(error);
DoxLogger.danger(stackTrace.toString());
};

Map<Type, Function()> get formRequests => <Type, Function()>{};

List<dynamic> get globalMiddleware => <dynamic>[];

List<Router> get routers;

CORSConfig get cors;

CacheConfig get cacheConfig => CacheConfig();
void defaultErrorHandler(Object? error, StackTrace stackTrace) {
DoxLogger.warn(error);
DoxLogger.danger(stackTrace.toString());
}

FileStorageConfig get fileStorageConfig => FileStorageConfig();
class AppConfig {
final String appKey;
final int serverPort;
final int totalIsolate;
final ResponseHandlerInterface? responseHandler;
final Function(Object?, StackTrace) errorHandler;
final Map<Type, FormRequest Function()> formRequests;
final List<dynamic> globalMiddleware;
final List<Router> routers;
final CORSConfig cors;
final CacheConfig cache;
final FileStorageConfig fileStorage;
final List<DoxService> services;

AppConfig({
required this.appKey,
this.serverPort = 3000,
this.totalIsolate = 3,
this.services = const <DoxService>[],
this.formRequests = const <Type, FormRequest Function()>{},
this.globalMiddleware = const <dynamic>[],
this.routers = const <Router>[],
this.cors = const CORSConfig(),
this.cache = const CacheConfig(),
this.fileStorage = const FileStorageConfig(),
this.errorHandler = defaultErrorHandler,
this.responseHandler,
});
}

class CORSConfig {
Expand Down Expand Up @@ -61,7 +68,7 @@ class FileStorageConfig {
final Map<String, StorageDriverInterface> drivers;

const FileStorageConfig({
this.defaultDriver = 'file',
this.defaultDriver = 'local',
this.drivers = const <String, StorageDriverInterface>{},
});
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import 'package:dox_core/dox_core.dart';

abstract class ResponseHandlerInterface {
const ResponseHandlerInterface();

dynamic handle(DoxResponse res);
}
Loading

0 comments on commit bb18bed

Please sign in to comment.