laconia icon indicating copy to clipboard operation
laconia copied to clipboard

feat: allow extensions of LaconiaContext and Error types

Open kirbyjs opened this issue 3 years ago • 3 comments

Description

  • add the ability to extend LaconiaContext and Error 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

kirbyjs avatar Nov 09 '21 02:11 kirbyjs

@all-contributors please add @kirbyjs for code

ceilfors avatar Nov 10 '21 13:11 ceilfors

@ceilfors

I've put up a pull request to add @kirbyjs! :tada:

allcontributors[bot] avatar Nov 10 '21 13:11 allcontributors[bot]

@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).

ceilfors avatar Nov 10 '21 13:11 ceilfors