Type improvements

Summary: some type simplifications, that makes it easier to reuse data sources and helps type inference

Reviewed By: passy

Differential Revision: D28413380

fbshipit-source-id: 261a8b981bf18a00edc3075926bd668322e1c37d
This commit is contained in:
Michel Weststrate
2021-06-07 08:08:53 -07:00
committed by Facebook GitHub Bot
parent 9a2677fc24
commit bc647972e1
12 changed files with 80 additions and 76 deletions

View File

@@ -7,20 +7,17 @@
* @format
*/
import {DataSource, ExtractKeyType} from '../data-source/index';
import {
DataSource,
createDataSource as baseCreateDataSource,
DataSourceOptions as BaseDataSourceOptions,
} from '../data-source/index';
import {registerStorageAtom} from '../plugin/PluginBase';
type CreateDataSourceOptions<T, K extends keyof T> = {
/**
* If a key is set, the given field of the records is assumed to be unique,
* and it's value can be used to perform lookups and upserts.
*/
key?: K;
/**
* The maximum amount of records that this DataSource will store.
* If the limit is exceeded, the oldest records will automatically be dropped to make place for the new ones
*/
limit?: number;
type CreateDataSourceOptions<T, K extends keyof T> = BaseDataSourceOptions<
T,
K
> & {
/**
* Should this state persist when exporting a plugin?
* If set, the dataSource will be saved / loaded under the key provided
@@ -29,21 +26,15 @@ type CreateDataSourceOptions<T, K extends keyof T> = {
};
export function createDataSource<T, KEY extends keyof T = any>(
initialSet: T[],
initialSet: readonly T[],
options: CreateDataSourceOptions<T, KEY>,
): DataSource<T, KEY, ExtractKeyType<T, KEY>>;
export function createDataSource<T>(
initialSet?: T[],
): DataSource<T, never, never>;
): DataSource<T>;
export function createDataSource<T>(initialSet?: readonly T[]): DataSource<T>;
export function createDataSource<T, KEY extends keyof T>(
initialSet: T[] = [],
initialSet: readonly T[] = [],
options?: CreateDataSourceOptions<T, KEY>,
): DataSource<T, any, any> {
const ds = new DataSource<T, KEY>(options?.key);
if (options?.limit !== undefined) {
ds.limit = options.limit;
}
): DataSource<T> {
const ds = baseCreateDataSource(initialSet, options);
registerStorageAtom(options?.persist, ds);
initialSet.forEach((value) => ds.append(value));
return ds;
}