Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added dynamic assets typing. Has to be built at finish #3505

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 24 additions & 18 deletions src/assets/Assets.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import _ from 'lodash';

interface CustomObject {
[key: string]: any;
}
type NestedObject<Path extends string, U> = Path extends `${infer Key}.${infer Rest}`
? {[K in Key]: NestedObject<Rest, U>}
: {[K in Path]: U};

function assignProperties(a: CustomObject, b: {[key: string]: any}) {
function assignProperties(a: unknown, b: {[key: string]: any}) {
if (a) {
Object.keys(b).forEach(key => {
// @ts-ignore
Expand All @@ -15,7 +15,7 @@ function assignProperties(a: CustomObject, b: {[key: string]: any}) {
return a;
}

function ensurePath(obj: CustomObject, path: string) {
function ensurePath(obj: Record<string, any>, path: string) {
let pointer = obj;

const pathArray = path.split('.');
Expand All @@ -38,28 +38,34 @@ function ensurePath(obj: CustomObject, path: string) {
return pointer;
}

export class Assets {
[key: string]: any;
export const Assets = <T extends Record<string, unknown>>(initialAssets = {} as T) => {
const assets = initialAssets;

loadAssetsGroup(groupName: string, assets: object) {
const loadAssetsGroup = <Path extends string, U extends Record<string, unknown>>(
groupName: Path,
assetsToLoad: U
) => {
if (!_.isString(groupName)) {
throw new Error('group name should be a string');
}

if (!_.isPlainObject(assets)) {
if (!_.isPlainObject(assetsToLoad)) {
throw new Error('assets should be a hash map or a function (for lazy access)');
}

if (groupName === '') {
assignProperties(this, assets);
assignProperties(assets, assetsToLoad);
} else {
assignProperties(ensurePath(this, groupName), assets);
assignProperties(ensurePath(assets, groupName), assetsToLoad);
}
return Assets(assets as T & NestedObject<Path, U>);
};

return this;
}
const build = () => {
return assets;
};

getAssetByPath(path: string) {
return _.get(this, path);
}
}
return {
loadAssetsGroup,
build
};
};