typedserver/readme.md

250 lines
7.6 KiB
Markdown

# @api.global/typedserver
A TypeScript-based framework for serving static files with advanced features including live reloading, compression, and type-safe API requests. Part of the @api.global ecosystem, it integrates seamlessly with @api.global/typedrequest for type-safe HTTP requests and @api.global/typedsocket for WebSocket communication.
## Features
- **Type-Safe API Ecosystem**:
- HTTP Requests via @api.global/typedrequest
- WebSocket Support via @api.global/typedsocket
- Full TypeScript support across all endpoints
- **Service Worker Integration**: Advanced caching and offline capabilities
- **Edge Worker Support**: Optimized edge computing capabilities
- **Live Reload**: Automatic browser refresh on file changes
- **Compression**: Built-in support for response compression
- **CORS Management**: Flexible cross-origin resource sharing
- **TypeScript First**: Built with and for TypeScript
## Components
### Core Server (`ts/`)
- Static file serving with Express
- Type-safe request handling
- Live reload functionality
- Compression middleware
### Service Worker (`ts_web_serviceworker/`)
- `CacheManager`: Advanced caching strategies
- `NetworkManager`: Request/response handling
- `UpdateManager`: Cache invalidation and updates
- `ServiceWorker`: Core service worker implementation
### Edge Worker (`ts_edgeworker/`)
- Edge computing capabilities
- Request/response transformation
- Edge caching strategies
### Web Inject (`ts_web_inject/`)
- Live reload script injection
- Runtime dependency management
- Dynamic module loading
## Installation
```bash
npm install @api.global/typedserver
```
## Quick Start
```typescript
import { TypedServer } from '@api.global/typedserver';
const server = new TypedServer({
port: 3000,
serveDir: './public',
watch: true,
compression: true
});
server.start();
```
## Type-Safe API Integration
### HTTP Requests with TypedRequest
```typescript
import { TypedRequest } from '@api.global/typedrequest';
// Define your request/response interface
interface IUserRequest {
method: 'getUser';
request: { userId: string };
response: { username: string; email: string; };
}
// Create and use a typed request
const getUserRequest = new TypedRequest<IUserRequest>('/api/users', 'getUser');
const user = await getUserRequest.fire({ userId: '123' });
```
### WebSocket Communication
```typescript
import { TypedSocket } from '@api.global/typedsocket';
// Server setup
const typedRouter = new TypedRouter();
const server = await TypedSocket.createServer(typedRouter);
// Client connection
const client = await TypedSocket.createClient(typedRouter, 'ws://localhost:3000');
// Type-safe real-time messaging
interface IChatMessage {
method: 'sendMessage';
request: { text: string };
response: { id: string; timestamp: number; };
}
```
## Advanced Usage
### Service Worker Setup
```typescript
import { ServiceWorker } from '@api.global/typedserver/web_serviceworker';
const sw = new ServiceWorker({
cacheStrategy: 'network-first',
offlineSupport: true
});
sw.register();
```
### Edge Worker Configuration
```typescript
import { EdgeWorker } from '@api.global/typedserver/edgeworker';
const edge = new EdgeWorker({
transforms: ['compress', 'minify'],
caching: true
});
```
## Configuration
### Server Options
```typescript
interface IServerOptions {
port?: number;
host?: string;
serveDir: string;
watch?: boolean;
compression?: boolean;
cors?: boolean | CorsOptions;
cache?: CacheOptions;
}
```
### Cache Strategies
```typescript
type CacheStrategy =
| 'network-first'
| 'cache-first'
| 'stale-while-revalidate';
```
## API Reference
See [API Documentation](https://api.global/docs/typedserver) for detailed API reference.
## Contributing
1. Fork the repository
2. Create your feature branch
3. Commit your changes
4. Push to the branch
5. Create a Pull Request
## License
MIT License - see LICENSE for details.
Task Venture Capital GmbH © 2024
```typescript
// Define a request type
interface MyCustomRequest {
userId: string;
}
// Define a response type
interface MyCustomResponse {
userName: string;
}
```
Next, set up a route to handle requests using these types:
```typescript
import { TypedRouter, TypedHandler } from '@api.global/typedrequest';
// Instantiate a TypedRouter
const typedRouter = new TypedRouter();
// Register a route with request and response types
typedRouter.addTypedHandler<MyCustomRequest, MyCustomResponse>(
new TypedHandler('getUser', async (requestData) => {
// Implement your logic here. For example, fetch user data from a database.
const userData = { userName: 'John Doe' }; // Dummy implementation
return { response: userData };
})
);
// Bind the typed router to the server
typedServer.useTypedRouter(typedRouter);
// Now, the route is set up to handle requests with type checking
```
This example shows defining types for requests and responses, creating a `TypedRouter`, and adding a route with typed handling. This feature brings the benefits of TypeScript's static type checking to server-side logic, improving the development experience.
### Enabling SSL/TLS
To enable SSL/TLS, configure the `TypedServer` with the SSL options, including the paths to your SSL certificate and key files:
```typescript
const serverOptions = {
port: 443,
serveDir: 'public',
watch: true,
injectReload: true,
cors: true,
privateKey: fs.readFileSync('path/to/ssl/private.key'),
publicKey: fs.readFileSync('path/to/ssl/certificate.crt')
};
const typedServer = new TypedServer(serverOptions);
startServer().catch(console.error);
```
Replace `'path/to/ssl/private.key'` and `'path/to/ssl/certificate.crt'` with the actual paths to your SSL key and certificate files. This setup ensures that your server communicates over HTTPS, encrypting the data transmitted between the client and the server.
### Conclusion
`@api.global/typedserver` offers a streamlined way to set up a web server with TypeScript, featuring static file serving, live reloading, typed request/response handling, and SSL support. This guide covers the basic usage, but `TypedServer` is highly configurable, catering to various hosting and development needs.
```
For a deeper dive into the API and more advanced configurations, refer to the official documentation and type definitions included in the package.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.