laconia
laconia copied to clipboard
feat: allow extensions of LaconiaContext and Error types
Description
- add the ability to extend
LaconiaContext
andError
types
Extending Error
interface CustomError extends Error {
response: string
status: number
}
const adapter = apigateway({
errorMappings: {
'CustomError:*': (error: CustomError) => { // previously this would error because CustomError was not Error
return {
body: error.response,
statusCode: error.status
};
}
}
})
Extending LaconiaContext
So my motivation for this one is because LaconiaContext
is pretty loosely typed with [key: string]: any;
, I wanted a way to extend it to improve upon the typing. We might even eventually removing that type ([key: string]: any;
), but that would be a definite breaking change that would need more consideration.
import DynamodbService from './dyanmodb-service';
interface CustomInput {
id: string;
}
interface CustomContext extends LaconiaContext {
someDep?: Record<string, string>;
anotherDep?: string;
dynamodbService?: DynamodbService;
}
laconia(adapter((input: CustomInput, context: Required<CustomContext>) => { // also still works without the adapter
console.log(context.someDep.test.toUpperCase());
console.log(input.id.replace('-', ''));
return {};
}))
.register<CustomContext, Pick<CustomContext, 'someDep' | 'anotherDep'>>((context: CustomContext) => {
return {someDep: {}, anotherDep: 'test'};
})
.register<CustomContext, Pick<CustomContext, 'dynamodbService'>>((context: CustomContext) => {
return {dynamodbService: new DynamodbService()};
})
.register((context: any) => ({config: context.config})) // random example where it would still pass
.postProcessor((context: Required<CustomContext>) => {});
Other comments
This is the typescript playgroud that I was using to test the types
@all-contributors please add @kirbyjs for code
@kirbyjs Thanks for raising this PR! I like the idea that you could use type the Context object to be used in the app. I'm worried about breaking change. For example, the LaconiaFactory
is a public interface at the moment, the users might already use this interface, the change will break their usage.
I've however added this into v2.0.0 milestone (no plan on how and when it'll be worked on yet).