Skip to content

Commit

Permalink
feat(mvc): add cors
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielSchaffer committed Mar 13, 2019
1 parent e64ff6f commit 650ab4f
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/dandi/mvc/src/basic.options-handler.ts
@@ -0,0 +1,21 @@
import { Inject, Injectable } from '@dandi/core'
import { HttpMethod, MvcResponse, Route } from '@dandi/mvc'

import { OptionsHandler } from './options-handler'

const ALLOW_HEADER = 'Allow'

@Injectable(OptionsHandler)
export class BasicOptionsHandler implements OptionsHandler {

public handleRequest(@Inject(Route) route: Route, @Inject(MvcResponse) res: MvcResponse): void {
this.setAllowHeader(ALLOW_HEADER, route, res)
}

protected setAllowHeader(header: string, route: Route, res: MvcResponse): void {
const methods = new Set(route.siblingMethods)
methods.add(HttpMethod.options)
res.setHeader(ALLOW_HEADER, [...methods.values()].join(','))
}

}
21 changes: 21 additions & 0 deletions packages/dandi/mvc/src/cors-handler.ts
@@ -0,0 +1,21 @@
import { Inject, Injectable } from '@dandi/core'
import { MvcResponse, Route } from '@dandi/mvc'

import { BasicOptionsHandler } from './basic.options-handler'
import { OptionsHandler } from './options-handler'

export enum CorsHeader {
allowOrigin = 'Access-Control-Allow-Origin',
allowMethods = 'Access-Control-Allow-Methods',
allowHeaders = 'Access-Control-Allow-Headers',
maxAge = 'Access-Control-Max-Age',
}

@Injectable(OptionsHandler)
export class CorsHandler extends BasicOptionsHandler {

public async handleRequest(@Inject(Route) route: Route, @Inject(MvcResponse) res: MvcResponse): Promise<void> {
this.setAllowHeader(CorsHeader.allowMethods, route, res)
}

}
File renamed without changes.
11 changes: 11 additions & 0 deletions packages/dandi/mvc/src/options-handler.ts
@@ -0,0 +1,11 @@
import { InjectionToken } from '@dandi/core'

import { localOpinionatedToken } from './local-token'

export interface OptionsHandler {
handleRequest(...args: any[]): void | Promise<void>
}

export const OptionsHandler: InjectionToken<OptionsHandler> = localOpinionatedToken('OptionsHandler', {
multi: false,
})

0 comments on commit 650ab4f

Please sign in to comment.