@mini2/core 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/Readme.MD +476 -34
  2. package/package.json +1 -1
package/Readme.MD CHANGED
@@ -1,19 +1,37 @@
1
1
  # @mini2/core
2
2
 
3
- Mini Express Framework - Express.js tabanlı hafif ve modüler web framework'ü. TypeScript desteği, otomatik Swagger dokümantasyonu ve dependency injection özelliklerine sahiptir.
3
+ **Mini Express Framework** - Express.js tabanlı hafif ve modüler web framework'ü. TypeScript desteği, otomatik Swagger dokümantasyonu, dependency injection ve decorator tabanlı routing sistemi ile modern API geliştirme deneyimi sağlar.
4
4
 
5
- ## Kurulum
5
+ ## ✨ Özellikler
6
+
7
+ - 🚀 **Decorator Tabanlı Routing**: `@Get`, `@Post` gibi decorator'lar ile kolay route tanımlama
8
+ - 📝 **Otomatik Swagger Dokümantasyonu**: API dokümantasyonu otomatik oluşturulur
9
+ - 🔧 **Dependency Injection**: InversifyJS tabanlı güçlü DI container
10
+ - 🛡️ **Güvenlik Middleware'leri**: Authentication, authorization ve validation
11
+ - 📦 **Tam TypeScript Desteği**: Type-safe API geliştirme
12
+ - 🎯 **Response Builder**: Tutarlı API yanıtları
13
+ - ⚡ **Hızlı Kurulum**: Minimal konfigürasyon
14
+
15
+ ## 📦 Kurulum
6
16
 
7
17
  ```bash
8
18
  npm install @mini2/core
9
19
  ```
10
20
 
11
- ## Temel Kullanım
21
+ ### Peer Dependencies (Opsiyonel)
22
+
23
+ ```bash
24
+ # Eğer MongoDB kullanıyorsanız
25
+ npm install mongoose
26
+ ```
27
+
28
+ ## 🚀 Hızlı Başlangıç
29
+
30
+ ### 1. Temel Konfigürasyon
12
31
 
13
32
  ```typescript
14
33
  import { App, IConfig } from '@mini2/core';
15
34
 
16
- // Konfigürasyon
17
35
  const config: IConfig = {
18
36
  port: 3000,
19
37
  host: 'localhost',
@@ -22,55 +40,479 @@ const config: IConfig = {
22
40
 
23
41
  // Controller'ları tanımlayın
24
42
  const controllers = [
25
- // Controller sınıflarınız buraya gelecek
43
+ // Controller sınıflarınız
26
44
  ];
27
45
 
28
- // Uygulamayı başlatın
29
46
  const app = new App(controllers);
30
47
  await app.init(config);
31
48
  await app.afterInit();
32
49
  ```
33
50
 
34
- ## Özellikler
51
+ ### 2. Controller Oluşturma
52
+
53
+ ```typescript
54
+ import {
55
+ Controller,
56
+ Get,
57
+ Post,
58
+ ResponseBuilder,
59
+ validationMiddleware,
60
+ } from '@mini2/core';
61
+
62
+ @Controller('/api/users')
63
+ export class UserController {
64
+ @Get('/')
65
+ async getUsers() {
66
+ const users = await this.userService.findAll();
67
+ return new ResponseBuilder().ok(users);
68
+ }
69
+
70
+ @Post('/')
71
+ @Validation({ body: CreateUserDto })
72
+ async createUser(@Body() userData: CreateUserDto) {
73
+ const user = await this.userService.create(userData);
74
+ return new ResponseBuilder().created(user);
75
+ }
76
+
77
+ @Get('/:id')
78
+ @Authenticated()
79
+ @Authorized(['user:read'])
80
+ async getUser(@Param('id') id: string) {
81
+ const user = await this.userService.findById(id);
82
+ return new ResponseBuilder().ok(user);
83
+ }
84
+ }
85
+ ```
86
+
87
+ ## 📚 API Referansı
88
+
89
+ ### 🏗️ Ana Sınıflar
90
+
91
+ #### **App**
92
+
93
+ Ana uygulama sınıfı, Express server'ını yönetir.
94
+
95
+ ```typescript
96
+ import { App, IConfig } from '@mini2/core';
97
+
98
+ const app = new App(controllers);
99
+ await app.init(config); // Server'ı başlat
100
+ await app.afterInit(); // Başlangıç sonrası işlemler
101
+ ```
102
+
103
+ **Özellikler:**
35
104
 
36
- - 🚀 **Hızlı Kurulum**: Minimal konfigürasyon ile hızlıca başlayın
37
- - 📝 **Otomatik Swagger**: API dokümantasyonu otomatik olarak oluşturulur
38
- - 🔧 **Dependency Injection**: InversifyJS tabanlı DI container
39
- - 🛡️ **Middleware Desteği**: Authentication, authorization ve validation
40
- - 📦 **TypeScript**: Tam TypeScript desteği
41
- - 🎯 **Response Builder**: Tutarlı API yanıtları için yardımcı fonksiyonlar
105
+ - Express server yönetimi
106
+ - Middleware konfigürasyonu
107
+ - Swagger dokümantasyon entegrasyonu
108
+ - Controller routing sistemi
42
109
 
43
- ## API Referansı
110
+ #### **Container & container**
44
111
 
45
- ### Ana Sınıflar
112
+ Dependency injection için InversifyJS container'ları.
46
113
 
47
- - **App**: Ana uygulama sınıfı
48
- - **Container**: Dependency injection container'ı
114
+ ```typescript
115
+ import { Container, container } from '@mini2/core';
49
116
 
50
- ### Arayüzler (Interfaces)
117
+ // Yeni container oluştur
118
+ const myContainer = new Container();
119
+ myContainer.bind('UserService').to(UserService);
51
120
 
52
- - **IApp**: Uygulama arayüzü
53
- - **IConfig**: Konfigürasyon arayüzü
54
- - **IAuthenticated**: Authentication arayüzü
55
- - **IQueue**: Queue işlemleri arayüzü
56
- - **IRepository**: Repository pattern arayüzü
121
+ // Hazır container kullan
122
+ container.bind('UserService').to(UserService);
123
+ ```
57
124
 
58
- ### Middleware'ler
125
+ ### 📋 Arayüzler (Interfaces)
59
126
 
60
- - **AuthenticatedMiddleware**: Kimlik doğrulama middleware'i
61
- - **AuthorizedMiddleware**: Yetkilendirme middleware'i
62
- - **ValidationMiddleware**: Veri validasyon middleware'i
127
+ #### **IConfig**
63
128
 
64
- ### Yardımcı Fonksiyonlar
129
+ ```typescript
130
+ interface IConfig {
131
+ host: string; // Server host adresi
132
+ port: number; // Server portu
133
+ applicationName: string; // Uygulama adı
134
+ }
135
+ ```
65
136
 
66
- - **ArrayUnify**: Dizi birleştirme yardımcıları
67
- - **Math**: Matematik işlemleri
68
- - **ResponseBuilder**: API yanıt oluşturucu
137
+ #### **IApp**
69
138
 
70
- ## Lisans
139
+ ```typescript
140
+ interface IApp {
141
+ init(config: IConfig): Promise<void>;
142
+ afterInit(): Promise<void>;
143
+ }
144
+ ```
145
+
146
+ #### **IRepository<IdentifierType, ModelType>**
147
+
148
+ Generic repository pattern interface'i.
149
+
150
+ ```typescript
151
+ interface IRepository<IdentifierType, ModelType> {
152
+ findAll(): Promise<(ModelType & TimestampFields)[]>;
153
+ findById(id: IdentifierType): Promise<(ModelType & TimestampFields) | null>;
154
+ create(item: ModelType): Promise<ModelType & TimestampFields>;
155
+ update(
156
+ id: IdentifierType,
157
+ item: Partial<ModelType>
158
+ ): Promise<ModelType & TimestampFields>;
159
+ delete(id: IdentifierType): Promise<void>;
160
+ findPaginated(
161
+ query: Partial<ModelType>,
162
+ page: number,
163
+ limit: number
164
+ ): Promise<(ModelType & TimestampFields)[]>;
165
+ mapper(model: any): ModelType & TimestampFields;
166
+ }
167
+ ```
168
+
169
+ #### **IResponseBuilder<T>**
170
+
171
+ ```typescript
172
+ interface IResponseBuilder<T = any> {
173
+ status: number;
174
+ data: T;
175
+ headers: Record<string, string>;
176
+ isFile: boolean;
177
+
178
+ ok(data: T): IResponseBuilder<T>;
179
+ created(data: T): IResponseBuilder<T>;
180
+ setHeader(key: string, value: string): IResponseBuilder<T>;
181
+ setHeaders(headers: Record<string, string>): IResponseBuilder<T>;
182
+ asFile(): IResponseBuilder<T>;
183
+ build(res: Response): void;
184
+ }
185
+ ```
186
+
187
+ ### 🛡️ Middleware'ler
188
+
189
+ #### **validationMiddleware**
190
+
191
+ Class-validator tabanlı veri doğrulama.
192
+
193
+ ```typescript
194
+ import { validationMiddleware } from '@mini2/core';
195
+
196
+ // Controller içinde
197
+ @Post('/users')
198
+ @Validation({ body: CreateUserDto })
199
+ async createUser(@Body() data: CreateUserDto) {
200
+ // Doğrulanmış data burada kullanılabilir
201
+ }
202
+ ```
203
+
204
+ **Desteklenen Validasyon Türleri:**
205
+
206
+ - `body` - Request body doğrulama
207
+ - `params` - URL parametreleri doğrulama
208
+ - `query` - Query parametreleri doğrulama
209
+
210
+ #### **authenticatedMiddleware**
211
+
212
+ Kimlik doğrulama kontrolü.
213
+
214
+ ```typescript
215
+ import { authenticatedMiddleware, IAuthenticatedRequest } from '@mini2/core';
216
+
217
+ // Kullanım
218
+ @Get('/profile')
219
+ @Authenticated()
220
+ async getProfile(@Req() req: IAuthenticatedRequest) {
221
+ // req.authenticated === true kontrolü yapılır
222
+ }
223
+ ```
224
+
225
+ #### **authorizedMiddleware**
226
+
227
+ Yetkilendirme kontrolü.
228
+
229
+ ```typescript
230
+ import { authorizedMiddleware } from '@mini2/core';
231
+
232
+ // Kullanım
233
+ @Delete('/admin/users/:id')
234
+ @Authenticated()
235
+ @Authorized(['admin', 'user:delete'])
236
+ async deleteUser(@Param('id') id: string) {
237
+ // req.user.permissions kontrolü yapılır
238
+ }
239
+ ```
240
+
241
+ ### 🎯 Response Builder
242
+
243
+ HTTP yanıtlarını standardize etmek için kullanılır.
244
+
245
+ ```typescript
246
+ import { ResponseBuilder } from '@mini2/core';
247
+
248
+ // Temel kullanım
249
+ return new ResponseBuilder().ok({ message: 'Success', data: users });
250
+
251
+ // Başarılı kayıt
252
+ return new ResponseBuilder()
253
+ .created({ id: newUser.id })
254
+ .setHeader('Location', `/users/${newUser.id}`);
255
+
256
+ // Dosya yanıtı
257
+ return new ResponseBuilder()
258
+ .ok(fileBuffer)
259
+ .setHeader('Content-Type', 'application/pdf')
260
+ .asFile();
261
+
262
+ // Custom status ve header'lar
263
+ return new ResponseBuilder()
264
+ .status(202)
265
+ .setHeaders({
266
+ 'X-Process-Id': processId,
267
+ 'Cache-Control': 'no-cache',
268
+ })
269
+ .ok({ status: 'processing' });
270
+ ```
271
+
272
+ ### 🏷️ Decorator'lar
273
+
274
+ #### **HTTP Method Decorator'ları**
275
+
276
+ ```typescript
277
+ @Get('/path') // GET request
278
+ @Post('/path') // POST request
279
+ @Put('/path') // PUT request
280
+ @Delete('/path') // DELETE request
281
+ @Patch('/path') // PATCH request
282
+ ```
283
+
284
+ #### **Parameter Decorator'ları**
285
+
286
+ ```typescript
287
+ @Param('id') id: string // URL parametresi
288
+ @Body() data: CreateUserDto // Request body
289
+ @Query('page') page: number // Query parametresi
290
+ @Req() request: Request // Request objesi
291
+ @Res() response: Response // Response objesi
292
+ @Next() next: NextFunction // Next function
293
+ ```
294
+
295
+ #### **Middleware Decorator'ları**
296
+
297
+ ```typescript
298
+ @Authenticated() // Kimlik doğrulama gerekli
299
+ @Authorized(['admin']) // Yetkilendirme kontrolü
300
+ @Validation({ body: UserDto }) // Veri doğrulama
301
+ @Middleware(customMiddleware) // Custom middleware
302
+ ```
303
+
304
+ ### ⚠️ Exception Handling
305
+
306
+ Önceden tanımlanmış HTTP exception'ları.
307
+
308
+ ```typescript
309
+ import {
310
+ HttpException,
311
+ BadRequestException,
312
+ UnauthorizedException,
313
+ ForbiddenException,
314
+ NotFoundException,
315
+ // ... diğer exception'lar
316
+ } from '@mini2/core';
317
+
318
+ // Temel kullanım
319
+ throw new BadRequestException({
320
+ message: 'Invalid input data',
321
+ validationErrors: [{ field: 'email', errors: ['Invalid email format'] }],
322
+ });
323
+
324
+ // Custom exception
325
+ throw new HttpException(
326
+ {
327
+ message: 'Custom error message',
328
+ errorId: 1001,
329
+ },
330
+ 422
331
+ );
332
+ ```
333
+
334
+ **Mevcut Exception'lar:**
335
+
336
+ - `BadRequestException` (400)
337
+ - `UnauthorizedException` (401)
338
+ - `PaymentRequiredException` (402)
339
+ - `ForbiddenException` (403)
340
+ - `NotFoundException` (404)
341
+ - `MethodNotAllowedException` (405)
342
+ - `ConflictException` (409)
343
+ - `UnprocessableEntityException` (422)
344
+ - `TooManyRequestsException` (429)
345
+ - `InternalServerErrorException` (500)
346
+ - ve daha fazlası...
347
+
348
+ ### 🛠️ Yardımcı Fonksiyonlar
349
+
350
+ #### **arrayUnify**
351
+
352
+ Dizi elemanlarını birleştirir ve tekrarları kaldırır.
353
+
354
+ ```typescript
355
+ import { arrayUnify } from '@mini2/core';
356
+
357
+ const result = arrayUnify([1, 2, 2, 3, 1]); // [1, 2, 3]
358
+ ```
359
+
360
+ #### **Math Utilities**
361
+
362
+ ```typescript
363
+ import { sum } from '@mini2/core';
364
+
365
+ const result = sum(5, 3); // 8
366
+ ```
367
+
368
+ ### 📖 Swagger Entegrasyonu
369
+
370
+ Otomatik API dokümantasyonu oluşturulur.
371
+
372
+ ```typescript
373
+ // Swagger dokümantasyonu şu adreslerde mevcut:
374
+ // http://localhost:3000/api-docs - Swagger UI
375
+ // http://localhost:3000/api-docs.json - OpenAPI JSON
376
+ ```
377
+
378
+ **Swagger Konfigürasyonu:**
379
+
380
+ ```typescript
381
+ const swaggerOptions = {
382
+ title: config.applicationName,
383
+ description: `API documentation for ${config.applicationName}`,
384
+ version: '1.0.0',
385
+ servers: [{ url: `http://${config.host}:${config.port}` }],
386
+ docsPath: '/api-docs',
387
+ jsonPath: '/api-docs.json',
388
+ };
389
+ ```
390
+
391
+ ### 📝 TypeScript Desteği
392
+
393
+ Tam TypeScript desteği ile type-safe API geliştirme:
394
+
395
+ ```typescript
396
+ // DTO sınıfları
397
+ export class CreateUserDto {
398
+ @IsEmail()
399
+ email: string;
400
+
401
+ @IsString()
402
+ @MinLength(3)
403
+ name: string;
404
+
405
+ @IsOptional()
406
+ @IsNumber()
407
+ age?: number;
408
+ }
409
+
410
+ // Controller'da kullanım
411
+ @Post('/users')
412
+ @Validation({ body: CreateUserDto })
413
+ async createUser(@Body() userData: CreateUserDto): Promise<ResponseBuilder<User>> {
414
+ const user = await this.userService.create(userData);
415
+ return new ResponseBuilder<User>().created(user);
416
+ }
417
+ ```
418
+
419
+ ## 🔧 Gelişmiş Kullanım
420
+
421
+ ### Custom Middleware Ekleme
422
+
423
+ ```typescript
424
+ import { middleware } from '@mini2/core';
425
+
426
+ const loggerMiddleware = (req: Request, res: Response, next: NextFunction) => {
427
+ console.log(`${req.method} ${req.path}`);
428
+ next();
429
+ };
430
+
431
+ @Get('/users')
432
+ @Middleware(loggerMiddleware)
433
+ async getUsers() {
434
+ // Logger middleware otomatik çalışır
435
+ }
436
+ ```
437
+
438
+ ### Dependency Injection
439
+
440
+ ```typescript
441
+ import { Container, injectable, inject } from '@mini2/core';
442
+
443
+ @injectable()
444
+ export class UserService {
445
+ constructor(@inject('UserRepository') private userRepo: IUserRepository) {}
446
+ }
447
+
448
+ // Container konfigürasyonu
449
+ container.bind('UserRepository').to(UserRepository);
450
+ container.bind('UserService').to(UserService);
451
+ ```
452
+
453
+ ## 📋 Tam Export Listesi
454
+
455
+ ```typescript
456
+ // Ana sınıflar
457
+ export { App } from '@mini2/core';
458
+ export { Container, container } from '@mini2/core';
459
+
460
+ // Interfaces
461
+ export { IApp, IConfig, IRepository, IResponseBuilder } from '@mini2/core';
462
+
463
+ // Middleware'ler
464
+ export {
465
+ validationMiddleware,
466
+ authenticatedMiddleware,
467
+ authorizedMiddleware,
468
+ } from '@mini2/core';
469
+
470
+ // Utilities
471
+ export { arrayUnify, sum, ResponseBuilder } from '@mini2/core';
472
+
473
+ // Exception'lar
474
+ export {
475
+ HttpException,
476
+ BadRequestException,
477
+ UnauthorizedException,
478
+ // ... tüm exception'lar
479
+ } from '@mini2/core';
480
+
481
+ // Types ve decorators
482
+ export { MINI_TYPES } from '@mini2/core';
483
+ export {
484
+ Controller,
485
+ Get,
486
+ Post,
487
+ Put,
488
+ Delete,
489
+ Patch,
490
+ Body,
491
+ Param,
492
+ Query,
493
+ Req,
494
+ Res,
495
+ Next,
496
+ Authenticated,
497
+ Authorized,
498
+ Validation,
499
+ Middleware,
500
+ } from '@mini2/core';
501
+
502
+ // Swagger
503
+ export { SwaggerIntegration, SwaggerOptions } from '@mini2/core';
504
+ ```
505
+
506
+ ## 📄 Lisans
71
507
 
72
508
  ISC
73
509
 
74
- ## Yazar
510
+ ## 👨‍💻 Yazar
511
+
512
+ **Mustafa Çolakoğlu**
513
+ Email: mustafacolakoglu94@gmail.com
514
+ GitHub: https://github.com/mustafa-colakoglu
515
+
516
+ ---
75
517
 
76
- Mustafa Çolakoglu <mustafacolakoglu94@gmail.com>
518
+ **Not:** Bu framework aktif olarak geliştirilmektedir. Öneriler ve katkılar için GitHub repository'sini ziyaret edin.
package/package.json CHANGED
@@ -25,7 +25,7 @@
25
25
  "license": "ISC",
26
26
  "description": "Mini Express Framework - Lightweight and modular Express.js framework with TypeScript support",
27
27
  "name": "@mini2/core",
28
- "version": "1.0.7",
28
+ "version": "1.0.8",
29
29
  "author": "Mustafa Çolakoglu <mustafacolakoglu94@gmail.com> (https://github.com/mustafa-colakoglu)",
30
30
  "dependencies": {
31
31
  "class-transformer": "^0.5.1",