Friday, 19 April 2019

Best pattern for desiging a package that can be configured/initialized (similar to how aws-sdk works)

I would like to create a set of shared data models for multiple projects, so I'm creating a data models package. These data models also handle CRUD to some backends, so I also need to inject some config when I instantiate the package.I would also like to be able to import my models and inject the table names without the package having a dependency on environment variables (just like aws-sdk is imported and configured using a global config object), but I am not sure how that pattern works. My initial guess would be something like this... would this pattern work with annotations?// models-package/index.ts export configure = (config: Config) => { global.gConfig = config; } // models-package/book.ts (See the full version above, this is just how I would define the table name instead of relying on ENV) const _tableName = global.gConfig.BOOK_TABLE_NAME; class Book { ... save() { // You might be thinking that I should simply add _tableName as a parameter to "save", however, this is unfortunately not possible in my use case. _tableName is actually used as an annotation in an aws-data-mapper class. saveToTable(_tableName) } } ... // some-project/index.ts import models from 'models-package'; models.configure({BOOK_TABLE_NAME: 'books'});

Submitted April 19, 2019 at 07:42PM by 8solutions

No comments:

Post a Comment