Passed
Push — trunk ( 5039ac...c81c28 )
by Christian
12:05 queued 14s
created

  F

Complexity

Conditions 11

Size

Total Lines 159
Code Lines 106

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 106
dl 0
loc 159
rs 3.78
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like extension-data-handling.init.ts ➔ initializeExtensionDataLoader often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/**
2
 * @package admin
3
 */
4
5
import type { Entity } from '@shopware-ag/admin-extension-sdk/es/data/_internals/Entity';
6
import type EntityCollection from '../../core/data/entity-collection.data';
7
import type Repository from '../../core/data/repository.data';
8
9
function getRepository(
10
    entityName: keyof EntitySchema.Entities,
11
    additionalInformation: { _event_: MessageEvent<string>},
12
): Repository<keyof EntitySchema.Entities> | null {
13
    const extensionName = Object.keys(Shopware.State.get('extensions'))
14
        .find(key => Shopware.State.get('extensions')[key].baseUrl.startsWith(additionalInformation._event_.origin));
15
16
    if (!extensionName) {
17
        throw new Error(`Could not find a extension with the given event origin "${additionalInformation._event_.origin}"`);
18
    }
19
20
    const extension = Shopware.State.get('extensions')?.[extensionName];
21
    if (!extension) {
22
        return null;
23
    }
24
25
    if (extension.integrationId) {
26
        return Shopware.Service('repositoryFactory')
27
            .create(entityName, '', { 'sw-app-integration-id': extension.integrationId });
28
    }
29
30
    return Shopware.Service('repositoryFactory').create(entityName);
31
}
32
33
function rejectRepositoryCreation(entityName: string): unknown {
34
    // eslint-disable-next-line prefer-promise-reject-errors
35
    return Promise.reject(`Could not create repository for entity "${entityName}"`);
36
}
37
38
/**
39
 * @deprecated tag:v6.6.0 - Will be private
40
 */
41
export default function initializeExtensionDataLoader(): void {
42
    Shopware.ExtensionAPI.handle('repositorySearch', async (
43
        {
44
            entityName,
45
            criteria = new Shopware.Data.Criteria(),
46
            context,
47
        },
48
        additionalInformation,
49
    ) => {
50
        try {
51
            const repository = getRepository(entityName as keyof EntitySchema.Entities, additionalInformation);
52
53
            if (!repository) {
54
                return rejectRepositoryCreation(
55
                    entityName as keyof EntitySchema.Entities,
56
                ) as Promise<EntityCollection<keyof EntitySchema.Entities>>;
57
            }
58
59
            const mergedContext = { ...Shopware.Context.api, ...context };
60
61
            try {
62
                return await repository.search(criteria, mergedContext);
63
            } catch (e) {
64
                return Promise.reject(e);
65
            }
66
        } catch (error) {
67
            return Promise.reject(error);
68
        }
69
    });
70
71
    Shopware.ExtensionAPI.handle('repositoryGet', (
72
        {
73
            entityName,
74
            id,
75
            criteria = new Shopware.Data.Criteria(),
76
            context,
77
        },
78
        additionalInformation,
79
    ) => {
80
        const repository = getRepository(entityName as keyof EntitySchema.Entities, additionalInformation);
81
        if (!repository) {
82
            return rejectRepositoryCreation(entityName as keyof EntitySchema.Entities) as Promise<null>;
83
        }
84
85
        const mergedContext = { ...Shopware.Context.api, ...context };
86
87
        return repository.get(id, mergedContext, criteria);
88
    });
89
90
    Shopware.ExtensionAPI.handle('repositorySave', (
91
        {
92
            entityName,
93
            entity,
94
            context,
95
        },
96
        additionalInformation,
97
    ) => {
98
        const repository = getRepository(entityName as keyof EntitySchema.Entities, additionalInformation);
99
        if (!repository) {
100
            return rejectRepositoryCreation(entityName as keyof EntitySchema.Entities) as Promise<void>;
101
        }
102
103
        const mergedContext = { ...Shopware.Context.api, ...context };
104
105
        return repository.save(entity as Entity<keyof EntitySchema.Entities>, mergedContext) as Promise<void>;
106
    });
107
108
    Shopware.ExtensionAPI.handle('repositoryClone', (
109
        {
110
            entityName,
111
            behavior,
112
            entityId,
113
            context,
114
        },
115
        additionalInformation,
116
    ) => {
117
        const repository = getRepository(entityName as keyof EntitySchema.Entities, additionalInformation);
118
        if (!repository) {
119
            return rejectRepositoryCreation(entityName as keyof EntitySchema.Entities);
120
        }
121
122
        const mergedContext = { ...Shopware.Context.api, ...context };
123
124
        return repository.clone(entityId, mergedContext, behavior as $TSDangerUnknownObject);
125
    });
126
127
    Shopware.ExtensionAPI.handle('repositoryHasChanges', (
128
        {
129
            entityName,
130
            entity,
131
        },
132
        additionalInformation,
133
    ) => {
134
        const repository = getRepository(entityName as keyof EntitySchema.Entities, additionalInformation);
135
        if (!repository) {
136
            return rejectRepositoryCreation(entityName as keyof EntitySchema.Entities) as Promise<boolean>;
137
        }
138
139
        return repository.hasChanges(entity as Entity<keyof EntitySchema.Entities>);
140
    });
141
142
    Shopware.ExtensionAPI.handle('repositorySaveAll', (
143
        {
144
            entityName,
145
            entities,
146
            context,
147
        },
148
        additionalInformation,
149
    ) => {
150
        const repository = getRepository(entityName as keyof EntitySchema.Entities, additionalInformation);
151
        if (!repository) {
152
            return rejectRepositoryCreation(entityName as keyof EntitySchema.Entities)as Promise<void>;
153
        }
154
155
        const mergedContext = { ...Shopware.Context.api, ...context };
156
157
        return repository.saveAll(entities as EntityCollection<keyof EntitySchema.Entities>, mergedContext) as Promise<void>;
158
    });
159
160
    Shopware.ExtensionAPI.handle('repositoryDelete', (
161
        {
162
            entityName,
163
            entityId,
164
            context,
165
        },
166
        additionalInformation,
167
    ) => {
168
        const repository = getRepository(entityName as keyof EntitySchema.Entities, additionalInformation);
169
        if (!repository) {
170
            return rejectRepositoryCreation(entityName as keyof EntitySchema.Entities)as Promise<void>;
171
        }
172
173
        const mergedContext = { ...Shopware.Context.api, ...context };
174
175
        return repository.delete(entityId, mergedContext) as unknown as Promise<void>;
176
    });
177
178
    Shopware.ExtensionAPI.handle('repositoryCreate', (
179
        {
180
            entityName,
181
            entityId,
182
            context,
183
        },
184
        additionalInformation,
185
    ) => {
186
        const repository = getRepository(entityName as keyof EntitySchema.Entities, additionalInformation);
187
        if (!repository) {
188
            return rejectRepositoryCreation(
189
                entityName as keyof EntitySchema.Entities,
190
            ) as Promise<Entity<keyof EntitySchema.Entities>>;
191
        }
192
193
        const mergedContext = { ...Shopware.Context.api, ...context };
194
195
        return repository.create(mergedContext, entityId);
196
    });
197
}
198