diff --git a/README.md b/README.md index 235c114..fade5d1 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,23 @@ import { StatusCodeErrorMapper } from 'http-problem-details-mapper' const problem = StatusCodeErrorMapper.mapStatusCode(400) ``` +Similar to the `DefaultErrorMapper` there's also a `DefaultMappingStrategy` which you can use if you have no specific requirements regarding the mapping behavior. + +It can be used like this: + +```js +import { MapperRegistry, DefaultMappingStrategy } from 'http-problem-details-mapper' + +const strategy = new DefaultMappingStrategy( + new MapperRegistry() + .registerMapper(new NotFoundErrorMapper())) + +const error = new NotFoundError({ type: 'customer', id: '123' }) +const problem = strategy.map() + +console.log(problem) +``` + ## Running the tests ``` diff --git a/src/DefaultMappingStrategy.ts b/src/DefaultMappingStrategy.ts new file mode 100644 index 0000000..806e02f --- /dev/null +++ b/src/DefaultMappingStrategy.ts @@ -0,0 +1,21 @@ +import { ProblemDocument } from 'http-problem-details' +import { IMappingStrategy } from './IMappingStrategy' +import { MapperRegistry } from './MapperRegistry' + +export class DefaultMappingStrategy implements IMappingStrategy { + public readonly registry: MapperRegistry + + public constructor (registry: MapperRegistry) { + this.registry = registry + } + + public map (error: any): ProblemDocument | null { + const err = error + const errorMapper = this.registry.getMapper(error) + if (errorMapper) { + return errorMapper.mapError(err) + } + + return null + } +} diff --git a/src/index.ts b/src/index.ts index d5ac0cb..ff7c600 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,8 +4,10 @@ import { DefaultErrorMapper } from './DefaultErrorMapper' import { StatusCodeErrorMapper } from './StatusCodeErrorMapper' import { IMappingStrategy, MappingStrategy } from './IMappingStrategy' import { ErrorStatusCodes } from './ErrorStatusCodes' +import { DefaultMappingStrategy } from './DefaultMappingStrategy' export { + DefaultMappingStrategy, ErrorStatusCodes, ErrorMapper, IErrorMapper, diff --git a/test/DefaultMappingStrategyTests.ts b/test/DefaultMappingStrategyTests.ts new file mode 100644 index 0000000..d519253 --- /dev/null +++ b/test/DefaultMappingStrategyTests.ts @@ -0,0 +1,14 @@ +import { MapperRegistry, DefaultMappingStrategy } from '../src' +import 'should' + +describe('DefaultMappingStrategy', (): void => { + describe('When mapping a generic error', (): void => { + it('should return status code 500 problem', (done): void => { + const strategy = new DefaultMappingStrategy(new MapperRegistry()) + const problem = strategy.map(new Error())! + problem.should.have.property('type', 'about:blank') + problem.status.should.equal(500) + return done() + }) + }) +})