-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
channel.service.ts
292 lines (272 loc) · 11.4 KB
/
channel.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import { Injectable } from '@nestjs/common';
import {
CreateChannelInput,
CreateChannelResult,
CurrencyCode,
DeletionResponse,
DeletionResult,
UpdateChannelInput,
UpdateChannelResult,
} from '@vendure/common/lib/generated-types';
import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants';
import { ID, Type } from '@vendure/common/lib/shared-types';
import { unique } from '@vendure/common/lib/unique';
import { RequestContext } from '../../api/common/request-context';
import { ErrorResultUnion, isGraphQlErrorResult } from '../../common/error/error-result';
import { ChannelNotFoundError, EntityNotFoundError, InternalServerError } from '../../common/error/errors';
import { LanguageNotAvailableError } from '../../common/error/generated-graphql-admin-errors';
import { createSelfRefreshingCache, SelfRefreshingCache } from '../../common/self-refreshing-cache';
import { ChannelAware } from '../../common/types/common-types';
import { assertFound, idsAreEqual } from '../../common/utils';
import { ConfigService } from '../../config/config.service';
import { TransactionalConnection } from '../../connection/transactional-connection';
import { VendureEntity } from '../../entity/base/base.entity';
import { Channel } from '../../entity/channel/channel.entity';
import { ProductVariantPrice } from '../../entity/product-variant/product-variant-price.entity';
import { Session } from '../../entity/session/session.entity';
import { Zone } from '../../entity/zone/zone.entity';
import { CustomFieldRelationService } from '../helpers/custom-field-relation/custom-field-relation.service';
import { patchEntity } from '../helpers/utils/patch-entity';
import { GlobalSettingsService } from './global-settings.service';
/**
* @description
* Contains methods relating to {@link Channel} entities.
*
* @docsCategory services
*/
@Injectable()
export class ChannelService {
private allChannels: SelfRefreshingCache<Channel[], [RequestContext]>;
constructor(
private connection: TransactionalConnection,
private configService: ConfigService,
private globalSettingsService: GlobalSettingsService,
private customFieldRelationService: CustomFieldRelationService,
) {}
/**
* When the app is bootstrapped, ensure a default Channel exists and populate the
* channel lookup array.
*
* @internal
*/
async initChannels() {
await this.ensureDefaultChannelExists();
this.allChannels = await createSelfRefreshingCache({
name: 'ChannelService.allChannels',
ttl: this.configService.entityOptions.channelCacheTtl,
refresh: { fn: ctx => this.findAll(ctx), defaultArgs: [RequestContext.empty()] },
});
}
/**
* @description
* Assigns a ChannelAware entity to the default Channel as well as any channel
* specified in the RequestContext.
*/
async assignToCurrentChannel<T extends ChannelAware>(entity: T, ctx: RequestContext): Promise<T> {
const defaultChannel = await this.getDefaultChannel();
const channelIds = unique([ctx.channelId, defaultChannel.id]);
entity.channels = channelIds.map(id => ({ id })) as any;
return entity;
}
/**
* @description
* Assigns the entity to the given Channels and saves.
*/
async assignToChannels<T extends ChannelAware & VendureEntity>(
ctx: RequestContext,
entityType: Type<T>,
entityId: ID,
channelIds: ID[],
): Promise<T> {
const entity = await this.connection.getEntityOrThrow(ctx, entityType, entityId, {
relations: ['channels'],
});
for (const id of channelIds) {
const channel = await this.connection.getEntityOrThrow(ctx, Channel, id);
entity.channels.push(channel);
}
await this.connection.getRepository(ctx, entityType).save(entity as any, { reload: false });
return entity;
}
/**
* @description
* Removes the entity from the given Channels and saves.
*/
async removeFromChannels<T extends ChannelAware & VendureEntity>(
ctx: RequestContext,
entityType: Type<T>,
entityId: ID,
channelIds: ID[],
): Promise<T | undefined> {
const entity = await this.connection.getRepository(ctx, entityType).findOne(entityId, {
relations: ['channels'],
});
if (!entity) {
return;
}
for (const id of channelIds) {
entity.channels = entity.channels.filter(c => !idsAreEqual(c.id, id));
}
await this.connection.getRepository(ctx, entityType).save(entity as any, { reload: false });
return entity;
}
/**
* @description
* Given a channel token, returns the corresponding Channel if it exists, else will throw
* a {@link ChannelNotFoundError}.
*/
async getChannelFromToken(token: string): Promise<Channel> {
const allChannels = await this.allChannels.value();
if (allChannels.length === 1 || token === '') {
// there is only the default channel, so return it
return this.getDefaultChannel();
}
const channel = allChannels.find(c => c.token === token);
if (!channel) {
throw new ChannelNotFoundError(token);
}
return channel;
}
/**
* @description
* Returns the default Channel.
*/
async getDefaultChannel(): Promise<Channel> {
const allChannels = await this.allChannels.value();
const defaultChannel = allChannels.find(channel => channel.code === DEFAULT_CHANNEL_CODE);
if (!defaultChannel) {
throw new InternalServerError(`error.default-channel-not-found`);
}
return defaultChannel;
}
findAll(ctx: RequestContext): Promise<Channel[]> {
return this.connection
.getRepository(ctx, Channel)
.find({ relations: ['defaultShippingZone', 'defaultTaxZone'] });
}
findOne(ctx: RequestContext, id: ID): Promise<Channel | undefined> {
return this.connection
.getRepository(ctx, Channel)
.findOne(id, { relations: ['defaultShippingZone', 'defaultTaxZone'] });
}
async create(
ctx: RequestContext,
input: CreateChannelInput,
): Promise<ErrorResultUnion<CreateChannelResult, Channel>> {
const channel = new Channel(input);
const defaultLanguageValidationResult = await this.validateDefaultLanguageCode(ctx, input);
if (isGraphQlErrorResult(defaultLanguageValidationResult)) {
return defaultLanguageValidationResult;
}
if (input.defaultTaxZoneId) {
channel.defaultTaxZone = await this.connection.getEntityOrThrow(
ctx,
Zone,
input.defaultTaxZoneId,
);
}
if (input.defaultShippingZoneId) {
channel.defaultShippingZone = await this.connection.getEntityOrThrow(
ctx,
Zone,
input.defaultShippingZoneId,
);
}
const newChannel = await this.connection.getRepository(ctx, Channel).save(channel);
await this.customFieldRelationService.updateRelations(ctx, Channel, input, newChannel);
await this.allChannels.refresh(ctx);
return channel;
}
async update(
ctx: RequestContext,
input: UpdateChannelInput,
): Promise<ErrorResultUnion<UpdateChannelResult, Channel>> {
const channel = await this.findOne(ctx, input.id);
if (!channel) {
throw new EntityNotFoundError('Channel', input.id);
}
const defaultLanguageValidationResult = await this.validateDefaultLanguageCode(ctx, input);
if (isGraphQlErrorResult(defaultLanguageValidationResult)) {
return defaultLanguageValidationResult;
}
const updatedChannel = patchEntity(channel, input);
if (input.defaultTaxZoneId) {
updatedChannel.defaultTaxZone = await this.connection.getEntityOrThrow(
ctx,
Zone,
input.defaultTaxZoneId,
);
}
if (input.defaultShippingZoneId) {
updatedChannel.defaultShippingZone = await this.connection.getEntityOrThrow(
ctx,
Zone,
input.defaultShippingZoneId,
);
}
await this.connection.getRepository(ctx, Channel).save(updatedChannel, { reload: false });
await this.customFieldRelationService.updateRelations(ctx, Channel, input, updatedChannel);
await this.allChannels.refresh(ctx);
return assertFound(this.findOne(ctx, channel.id));
}
async delete(ctx: RequestContext, id: ID): Promise<DeletionResponse> {
await this.connection.getEntityOrThrow(ctx, Channel, id);
await this.connection.getRepository(ctx, Session).delete({ activeChannelId: id });
await this.connection.getRepository(ctx, Channel).delete(id);
await this.connection.getRepository(ctx, ProductVariantPrice).delete({
channelId: id,
});
return {
result: DeletionResult.DELETED,
};
}
/**
* @description
* Type guard method which returns true if the given entity is an
* instance of a class which implements the {@link ChannelAware} interface.
*/
public isChannelAware(entity: VendureEntity): entity is VendureEntity & ChannelAware {
const entityType = Object.getPrototypeOf(entity).constructor;
return !!this.connection.rawConnection
.getMetadata(entityType)
.relations.find(r => r.type === Channel && r.propertyName === 'channels');
}
/**
* There must always be a default Channel. If none yet exists, this method creates one.
* Also ensures the default Channel token matches the defaultChannelToken config setting.
*/
private async ensureDefaultChannelExists() {
const { defaultChannelToken } = this.configService;
const defaultChannel = await this.connection.getRepository(Channel).findOne({
where: {
code: DEFAULT_CHANNEL_CODE,
},
});
if (!defaultChannel) {
const newDefaultChannel = new Channel({
code: DEFAULT_CHANNEL_CODE,
defaultLanguageCode: this.configService.defaultLanguageCode,
pricesIncludeTax: false,
currencyCode: CurrencyCode.USD,
token: defaultChannelToken,
});
await this.connection.getRepository(Channel).save(newDefaultChannel, { reload: false });
} else if (defaultChannelToken && defaultChannel.token !== defaultChannelToken) {
defaultChannel.token = defaultChannelToken;
await this.connection.getRepository(Channel).save(defaultChannel, { reload: false });
}
}
private async validateDefaultLanguageCode(
ctx: RequestContext,
input: CreateChannelInput | UpdateChannelInput,
): Promise<LanguageNotAvailableError | undefined> {
if (input.defaultLanguageCode) {
const availableLanguageCodes = await this.globalSettingsService
.getSettings(ctx)
.then(s => s.availableLanguages);
if (!availableLanguageCodes.includes(input.defaultLanguageCode)) {
return new LanguageNotAvailableError(input.defaultLanguageCode);
}
}
}
}