Skip to content

Commit

Permalink
chore: introduce type to prevent potential issues (#5066)
Browse files Browse the repository at this point in the history
## About the changes
This small improvement aims to help developers when instantiating
services. They need to be constructed without injecting services or
stores created elsewhere so they can be bound to the same transactional
scope.

This suggests that you need to create the services and stores on your
own
  • Loading branch information
gastonfournier authored Oct 17, 2023
1 parent cf42a82 commit db04a1e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
11 changes: 10 additions & 1 deletion src/lib/db/transaction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Knex } from 'knex';
import { IUnleashConfig } from 'lib/server-impl';

export type KnexTransaction = Knex.Transaction;

Expand Down Expand Up @@ -26,7 +27,15 @@ export const createKnexTransactionStarter = (
return transaction;
};

export type DbServiceFactory<S> = (db: Knex) => S;
export type DeferredServiceFactory<S> = (db: Knex) => S;
/**
* Services need to be instantiated with a knex instance on a per-transaction basis.
* Limiting the input parameters, makes sure we don't inject already instantiated services
* that might be bound to a different transaction.
*/
export type ServiceFactory<S> = (
config: IUnleashConfig,
) => DeferredServiceFactory<S>;
export type WithTransactional<S> = S & {
transactional: <R>(fn: (service: S) => R) => Promise<R>;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import {
createFakePrivateProjectChecker,
createPrivateProjectChecker,
} from '../private-project/createPrivateProjectChecker';
import { DbServiceFactory } from 'lib/db/transaction';
import { DeferredServiceFactory } from 'lib/db/transaction';
import { DependentFeaturesReadModel } from '../dependent-features/dependent-features-read-model';
import { FakeDependentFeaturesReadModel } from '../dependent-features/fake-dependent-features-read-model';
import {
Expand Down Expand Up @@ -149,7 +149,7 @@ export const createFakeExportImportTogglesService = (

export const deferredExportImportTogglesService = (
config: IUnleashConfig,
): DbServiceFactory<ExportImportService> => {
): DeferredServiceFactory<ExportImportService> => {
return (db: Db) => {
const { eventBus, getLogger, flagResolver } = config;
const importTogglesStore = new ImportTogglesStore(db);
Expand Down

0 comments on commit db04a1e

Please sign in to comment.