Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CORS helper #153

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions packages/core/micro-server/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,54 @@
# @alwatr/micro-server

Elegant powerful nodejs server for microservice use cases, written in tiny TypeScript module.

## Usage

### Create server

```typescript
import {AlwatrMicroServer} from '@alwatr/micro-server';

import type {AlwatrConnection} from '@alwatr/micro-server';

const app = new AlwatrMicroServer(8000);

app.route('all', '/', async (connection: AlwatrConnection) => {
connection.reply({
ok: true,
statusCode: 200,
data: {
app: 'Alwatr Microservice',
message: 'Hello ;)',
},
});
});
```

### Middleware

#### CORS Helper

Read about [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

```typescript
app.route('all', '/', async (connection) => {
connection.reply(
{
ok: true,
statusCode: 200,
data: {
app: 'Alwatr Microservice',
message: 'Hello World',
},
},
{
corsHelper: {
allowOrigin: 'https://developer.mozilla.org', // That should not end with "/"
allowMethod: '*',
maxAge: 5 * 60, // 5 Minute
},
}
);
});
```
18 changes: 14 additions & 4 deletions packages/core/micro-server/src/micro-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import {createServer} from 'http';

import {alwatrRegisteredList, createLogger} from '@alwatr/logger';

import type {Methods, ReplyContent} from './type.js';
import {corsHelper} from './middleware/cors-helpers.js';

import type {Methods, ReplyContent, ResponseOptions} from './type.js';
import type {IncomingMessage, ServerResponse} from 'http';

alwatrRegisteredList.push({
Expand All @@ -14,7 +16,7 @@ export class AlwatrMicroServer {
protected logger = createLogger(`micro-server:${this.port}`);
protected server = createServer(this.handleRequest);

constructor(protected port: number, autoListen = true) {
constructor(protected port: number, autoListen = true, public options?: ResponseOptions) {
this.logger.logMethodArgs('new', {port, listen: autoListen});
this.server = createServer(this.handleRequest.bind(this));

Expand Down Expand Up @@ -90,7 +92,7 @@ export class AlwatrMicroServer {
return;
}

const connection = new AlwatrConnection(incomingMessage, serverResponse);
const connection = new AlwatrConnection(incomingMessage, serverResponse, this.options);
const route = connection.url.pathname;
const method = connection.incomingMessage.method?.toLowerCase();

Expand Down Expand Up @@ -143,7 +145,11 @@ export class AlwatrConnection {

readonly body = this._getRequestBody();

constructor(public incomingMessage: IncomingMessage, public serverResponse: ServerResponse) {
constructor(
public incomingMessage: IncomingMessage,
public serverResponse: ServerResponse,
public options?: ResponseOptions,
) {
this.logger.logMethodArgs('new', {method: incomingMessage.method, url: incomingMessage.url});
}

Expand Down Expand Up @@ -210,6 +216,10 @@ export class AlwatrConnection {
);
}

if (this.options?.corsHelper !== undefined) {
corsHelper(this.serverResponse, this.options?.corsHelper);
}

this.serverResponse.writeHead(content.statusCode ?? 200, {
'Content-Length': body.length,
'Content-Type': 'application/json',
Expand Down
33 changes: 33 additions & 0 deletions packages/core/micro-server/src/middleware/cors-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {CorsHelperHeader} from '../type';

import type {ServerResponse} from 'http';

/**
* Set CORS helper header.
* https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*/
export function corsHelper(response: ServerResponse, header: CorsHelperHeader): void {
if (header.allowOrigin !== undefined) {
response.setHeader('Access-Control-Allow-Origin', header.allowOrigin);
}

if (header.allowMethods !== undefined) {
response.setHeader('Access-Control-Allow-Methods', header.allowMethods);
}

if (header.allowHeaders !== undefined) {
response.setHeader('Access-Control-Allow-Headers', header.allowHeaders);
}

if (header.exposeHeaders !== undefined) {
response.setHeader('Access-Control-Expose-Headers', header.exposeHeaders);
}

if (header.allowCredentials !== undefined) {
response.setHeader('Access-Control-Allow-Credentials', String(header.allowCredentials));
}

if (header.maxAge !== undefined) {
response.setHeader('Access-Control-Max-Age', header.maxAge);
}
}
13 changes: 13 additions & 0 deletions packages/core/micro-server/src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ interface ReplySuccessContent {
data: Record<string, unknown>;
}

export interface ResponseOptions {
corsHelper?: CorsHelperHeader;
}

export interface CorsHelperHeader {
allowOrigin: string;
allowMethods?: string;
allowHeaders?: string;
exposeHeaders?: string;
allowCredentials?: boolean;
maxAge?: number;
}

export type ReplyContent = ReplyFailedContent | ReplySuccessContent;

export type Methods = ('all' | 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options') & string;
8 changes: 7 additions & 1 deletion packages/starter/microservice/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,10 @@ import {AlwatrMicroServer} from '@alwatr/micro-server';

import {config} from './config.js';

export const app = new AlwatrMicroServer(config.port);
export const app = new AlwatrMicroServer(config.port, undefined, {
corsHelper: {
allowOrigin: '*',
allowMethods: '*',
maxAge: 5 * 60, // 5 min
},
});
4 changes: 3 additions & 1 deletion packages/starter/microservice/src/route/echo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {app} from '../app.js';

app.route('post', '/echo', async (connection) => {
import type {AlwatrConnection} from '@alwatr/micro-server';

app.route('post', '/echo', async (connection: AlwatrConnection) => {
const jsonBody = await connection.requireJsonBody();
if (jsonBody == null) return;

Expand Down
4 changes: 3 additions & 1 deletion packages/starter/microservice/src/route/home.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {app} from '../app.js';

app.route('all', '/', async (connection) => {
import type {AlwatrConnection} from '@alwatr/micro-server';

app.route('all', '/', async (connection: AlwatrConnection) => {
connection.reply({
ok: true,
data: {
Expand Down