Welcome
Welcome to @rhtml documentation
diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/docs/404.html b/docs/404.html index af4126d..10e9193 100644 --- a/docs/404.html +++ b/docs/404.html @@ -1 +1,14 @@ -
We could not find what you were looking for.
Please contact the owner of the site that linked you to the original URL and let them know their link is broken.
Archive
Welcome to @rhtml documentation
Welcome to @rhtml documentation
Welcome to @rhtml documentation
Welcome to @rhtml documentation
Welcome to @rhtml documentation
Welcome to @rhtml documentation
Welcome to @rhtml documentation
5 minutes to learn the most important Docusaurus concepts.
Introduction
Introduction
Introduction
Testing a @Controller
In the context of the @rhtml/fastify
package, the @Controller
decorator plays a role similar to other web framework libraries like Express or NestJS. Here's an explanation of what @Controller
is and how it's used:
Controller Definition: The @Controller
decorator is used to define a controller within your application. Controllers are responsible for handling incoming HTTP requests and returning appropriate responses.
Routing: Controllers typically define routes for different HTTP methods (e.g., GET, POST, PUT, DELETE). Each route is associated with a specific endpoint URL and handler function within the controller.
+Request Handling: When a request matches a route defined by a controller, the corresponding handler function is invoked to process the request. Inside the handler function, you can access request parameters, headers, body, and other data, and perform any necessary processing or business logic.
+Response Generation: Controller handler functions are responsible for generating and returning HTTP responses to the client. This includes setting response headers, status codes, and sending back data or content in the response body.
+Middleware Support: Controllers in @rhtml/fastify
may support the use of middleware functions to intercept and process requests before they reach the controller handler functions. This allows for common functionality such as authentication, logging, or input validation to be applied to multiple routes within the controller.
Organizational Structure: Controllers help to organize your application's routes and request handling logic into logical units based on functionality or resource type. This improves code readability, maintainability, and scalability.
+In summary, the @Controller
decorator in @rhtml/fastify
is used to define HTTP request handlers and routes within your application, facilitating the development of web APIs or server-side applications.
import { Module } from '@rhtml/di';
import { FastifyModule, Controller, Route } from '@rhtml/fastify';
import fastify from 'fastify';
@Module({
imports: [
FastifyModule.forRoot(fastify, {
server: {
port: 3000,
host: 'localhost',
},
}),
],
bootstraps: [HealthCheckController],
})
export class AppModule {}
@Controller({
route: '/status',
})
export class HealthCheckController {
@Route({
method: 'GET',
})
healthCheck(
request: FastifyRequest<{
Params: { myParams: string };
Body: { myBody: string };
Querystring: { myQueryString: string };
}>
) {
request.body.myBody;
request.query.myQueryString;
request.params.myParams;
return {
server: {
status: 'working',
},
};
}
}
import { Controller, Route } from '@rhtml/fastify';
@Controller({
route: '/status',
})
export class HealthCheckController {
@Route({
method: 'GET',
schema: {
body: {
$id: 'MyBody.json',
title: 'MyBody',
type: 'object',
properties: {},
required: [],
},
response: {
200: {
$id: 'MyResponse.json',
title: 'MyResponse',
type: 'object',
properties: {
status: {
type: 'string',
minLength: 1,
},
},
required: ['status'],
},
},
},
})
myRequest(
request: FastifyRequest<{
Body: { myBody: string };
}>
) {
return {
status: 'working',
};
}
}
path
parameterimport { Controller, Route } from '@rhtml/fastify';
import { FastifyRequest } from 'fastify';
@Controller({
route: '/status',
})
export class MyCustomController {
@Route({
method: 'GET',
url: '/:myParam',
})
myRequest(
request: FastifyRequest<{
Params: { myParam: string };
}>
) {
request.params.myParam;
return {
status: 'working',
};
}
}
The @Module()
decorator is used to define modules within your application. These modules help organize and encapsulate related functionality.
Provider Registration: Inside the providers
array passed to @Module()
, you list the various providers or services.
+These providers could include any objects or services needed within the module.
Dependency Injection Context: By specifying providers within a module, you're registering them with the dependency injection (DI) system of @rhtml
. This enables the framework to manage the creation and injection of dependencies throughout your application.
Organizational Structure: Using modules helps maintain a well-organized codebase, especially as the application grows. Each module in @rhtml
could encapsulate a specific set of features or functionalities, making the codebase easier to understand and maintain.
import { Module } from '@rhtml/di';
@Module({
imports: [],
providers: [],
bootstraps: [],
})
export class AppModule {}
import { Module } from '@rhtml/di';
@Module()
export class MyModule {}
@Module({
imports: [MyModule],
})
export class AppModule {}
import { Module, Injectable } from '@rhtml/di';
@Injectable()
export class MyProvider {}
@Module({
providers: [MyProvider],
})
export class AppModule {}
InjectionToken
and usage inside a Service Providerimport { Module, Injectable, InjectionToken } from '@rhtml/di';
export const MyInjectable = new InjectionToken();
export type MyInjectable = { myValue: string };
@Module({
providers: [
{
provide: MyInjectable,
useFactory: () => ({ myValue: '1234' }),
},
],
})
export class AppModule {}
@Injectable()
export class MyService {
constructor(@Inject(MyInjectable) private myInjectable: MyInjectable) {}
}
Controller
using @rhtml/fastify
packageimport { Module } from '@rhtml/di';
import { FastifyModule, Controller, Route } from '@rhtml/fastify';
@Module({
imports: [
FastifyModule.forRoot({
server: {
port: 3000,
host: 'localhost',
},
}),
],
bootstraps: [HealthCheckController],
})
export class AppModule {}
@Controller({
route: '/status',
})
export class HealthCheckController {
@Route({
method: 'GET',
})
healthCheck() {
return {
server: {
status: 'working',
},
};
}
}
import { Module, Injectable, Bootstrap } from '@rhtml/di';
@Injectable()
export class MyProvider {}
@Module({
providers: [MyProvider],
})
export class AppModule {}
Bootstrap(AppModule)
.then(() => console.log('Application started'))
.catch((e) => console.error(e));
Service Declaration: The @Injectable
decorator is used to declare a class as a service within your application. Services typically encapsulate reusable functionality, such as data access, logging, or business logic.
Dependency Injection Support: When a class is decorated with @Injectable
, it signals to the dependency injection container that instances of this class may be injected into other classes or components within your application. This allows you to use dependency injection to manage the instantiation and lifecycle of the service.
Constructor Injection: Services decorated with @Injectable
typically utilize constructor injection to receive their dependencies. This promotes loose coupling and makes the service easier to test.
Providing Dependencies: Services decorated with @Injectable
can have their dependencies automatically resolved and injected by the dependency injection container. This simplifies the process of managing dependencies and promotes modular, reusable code.
Lifecycle Management: Services decorated with @Injectable
support lifecycle hooks such as initialization, destruction. These hooks allow you to perform setup or cleanup tasks when the service is created or destroyed.
class
Providerimport { Injectable } from '@rhtml/di';
@Injectable()
export class MyProvider {
myMethod() {
return 'Hello World';
}
}
InjectionToken
into a Provider, first we need to define it in the respective Module++NOTE: Custom injection tokens can be also
+async
by usinguseFactory: async () => ({ myValue: '1234' })
++NOTE: When injection token is
+async
the application will not Bootstrap until everyasync
provider returns value
import { Module, Injectable, InjectionToken } from '@rhtml/di';
export const MyInjectable = new InjectionToken();
export type MyInjectable = { myValue: string };
@Module({
providers: [
{
provide: MyInjectable,
useFactory: () => ({ myValue: '1234' }),
},
],
})
export class AppModule {}
@Injectable()
export class MyProvider {
constructor(@Inject(MyInjectable) private myInjectable: MyInjectable) {}
myMethod() {
return this.myInjectable.myValue; // '1234'
}
}
import { Module, Injectable, InjectionToken } from '@rhtml/di';
@Module({
providers: [MyProvider, MyProviderSecond],
})
export class AppModule {}
@Injectable()
export class MyProvider {
myMethod() {
return '1234';
}
}
@Injectable()
export class MyProviderSecond {
constructor(private myProvider: MyProvider) {}
myMethod() {
return '1234';
}
}
import { Injectable, OnInit, OnDestroy } from '@rhtml/di';
@Injectable()
export class MyClass implements OnInit, OnDestroy {
OnInit() {
// When class is instantiated
}
OnDestroy() {
// When class is about to be removed from the DI container
}
}
@Controller
import { Bootstrap, get, Module } from '@rhtml/di';
import { FastifyModule } from '@rhtml/fastify';
import fastify from 'fastify';
import { HealthCheckController } from './healthcheck.controller';
import { HealthCheckService } from './healthcheck.service';
import { HealthCheckStatus } from './types';
describe('healthcheck controller', () => {
let healthCheckController: HealthCheckController;
let healthCheckService: HealthCheckService;
beforeEach(async () => {
@Module({
imports: [
FastifyModule.forRoot(fastify, {
logger: true,
}),
],
providers: [HealthCheckService],
bootstrap: [HealthCheckController],
})
class AppModule {}
await Bootstrap(AppModule);
healthCheckController = get(HealthCheckController);
healthCheckService = get(HealthCheckService);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should be defined', () => {
expect(healthCheckController).toBeDefined();
});
it('should call the healthcheck service', async () => {
const response = {
server: { status: HealthCheckStatus.WORKING },
database: { status: 'ok' },
} as never;
const spy = jest
.spyOn(healthCheckService, 'checkServicesStatus')
.mockResolvedValue(response);
const result = await healthCheckController.healthCheck();
expect(spy).toHaveBeenCalled();
expect(result).toEqual(response);
});
});
The provided TypeScript code is a test suite written using the Jest framework for testing. It tests a controller called HealthCheckController
, which utilizes @rhtml/di
for dependency injection and @rhtml/fastify
for web server functionality.
@rhtml/di
: Used for dependency injection.@rhtml/fastify
: Used for integrating Fastify with the application.fastify
: Represents the Fastify instance.jest
: Testing framework.describe()
function is used to group test cases related to the "healthcheck controller".healthCheckController
and healthCheckService
are declared outside the beforeEach()
block to make them accessible across test cases.beforeEach()
, a module (AppModule
) is defined using @Module
decorator from @rhtml/di
. It imports FastifyModule.forRoot()
from @rhtml/fastify
to configure Fastify.HealthCheckService
is registered as a provider within the module.Bootstrap(AppModule)
is awaited to initialize the module.HealthCheckController
and HealthCheckService
are obtained using get()
function from @rhtml/di
and assigned to healthCheckController
and healthCheckService
respectively.jest.restoreAllMocks()
is used in the afterEach()
block to restore all mocked functions after each test case.healthCheckController
is defined.healthCheck()
method of HealthCheckController
calls the checkServicesStatus()
method of HealthCheckService
. It mocks the checkServicesStatus()
method using jest.spyOn()
and verifies if it's called.healthCheckController.healthCheck()
matches the expected response.Overall, this code tests the behavior of the HealthCheckController
by mocking its dependencies and ensuring that it interacts correctly with the HealthCheckService
. It validates that the controller functions as expected when handling health check requests.
@Service
import { Bootstrap, Module, set } from '@rhtml/di';
import { HealthCheckService } from './healthcheck.service';
import { HealthCheckStatus } from './types';
describe('health check service', () => {
let healthCheckService: HealthCheckService;
beforeEach(async () => {
@Module({
providers: [HealthCheckService],
})
class AppModule {}
await Bootstrap(AppModule);
healthCheckService = set(HealthCheckService);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should return WORKING status for the server and the correct status for the database', () => {
const response = {
server: {
status: HealthCheckStatus.WORKING,
},
} as never;
const result = healthCheckService.checkServicesStatus();
expect(result).toEqual(response);
});
});
The provided TypeScript code is a test suite written using the Jest framework for testing. It tests a service called HealthCheckService
, which utilizes @rhtml/di
for dependency injection.
@rhtml/di
.describe()
function is used to group test cases related to the "health check service".healthCheckService
is declared outside the beforeEach()
block to make it accessible across test cases.beforeEach()
, a module (AppModule
) is defined using @Module
decorator from @rhtml/di
. It only provides the HealthCheckService
as a provider.Bootstrap(AppModule)
is awaited to initialize the module.set()
function from @rhtml/di
is used to obtain an instance of HealthCheckService
and assign it to healthCheckService
.jest.restoreAllMocks()
is used in the afterEach()
block to restore all mocked functions after each test case.checkServicesStatus()
method of HealthCheckService
returns the expected response.response
object with the expected structure and values.checkServicesStatus()
method and assigns the result to result
.result
matches the response
object using expect().toEqual()
.Overall, this code tests the behavior of the HealthCheckService
by verifying that its checkServicesStatus()
method returns the expected response. It ensures that the service functions correctly when checking the status of services.
The @rhtml/di
npm library is likely a dependency injection (DI) library for JavaScript or TypeScript projects. Dependency injection is a software design pattern used to manage dependencies between different components of an application.
Dependency Management: @rhtml/di
provides a way to manage dependencies between different parts of your application. Instead of hard-coding dependencies within a component, you define them externally, typically in a configuration file or through code annotations.
Injection: The library facilitates the injection of dependencies into components. When a component needs access to another object or service, it doesn't create that dependency itself; rather, it receives it from the DI container. This promotes loose coupling between components and makes them easier to replace or modify.
+Configuration: @rhtml/di
likely offers a configuration mechanism where you specify how dependencies are wired together. This could involve defining bindings between interfaces and concrete implementations, setting up lifecycle management for objects, and handling scopes (e.g., singleton instances vs. transient objects).
Scoping: Dependency injection containers often support different scopes for objects. For instance, you might want a singleton instance of a service that's shared across your application, while other objects are created anew each time they're needed.
+Testing: DI facilitates unit testing by allowing you to inject mock or fake dependencies into components during testing. This makes it easier to isolate and test individual parts of your application.
+Maintainability: By decoupling components from their dependencies, @rhtml/di
promotes better code organization and maintainability. Changes to one part of the system are less likely to have ripple effects throughout the codebase.
Overall, @rhtml/di
likely aims to simplify the management of dependencies in your JavaScript or TypeScript projects, leading to more modular, scalable, and maintainable code.
Programming can be easy using @rhtml
Docusaurus was designed from the ground up to be easily installed and used to get your website up and running quickly.
Docusaurus lets you focus on your docs, and we'll do the chores. Go ahead and move your docs into the docs
directory.
Extend or customize your website layout by reusing React. Docusaurus can be extended while reusing the same header and footer.