Skip to content

Commit

Permalink
fix(core): Correct typing of GraphQL ID type in generated code
Browse files Browse the repository at this point in the history
Fixes #410

BREAKING CHANGE: The `ID` type in `@vendure/common/lib/generated-types` & `@vendure/common/lib/generated-shop-types` is now correctly typed as `string | number`, whereas previously it was `string`. If you are using any generated types in your plugin code, this may lead to TypeScript compiler errors which will need to be corrected.
  • Loading branch information
michaelbromley committed Aug 26, 2020
1 parent d6a6cc0 commit dc7b303
Show file tree
Hide file tree
Showing 19 changed files with 91 additions and 84 deletions.
1 change: 1 addition & 0 deletions packages/admin-ui/src/lib/core/src/public_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ export * from './shared/dynamic-form-inputs/date-form-input/date-form-input.comp
export * from './shared/dynamic-form-inputs/dynamic-form-input/dynamic-form-input.component';
export * from './shared/dynamic-form-inputs/facet-value-form-input/facet-value-form-input.component';
export * from './shared/dynamic-form-inputs/number-form-input/number-form-input.component';
export * from './shared/dynamic-form-inputs/password-form-input/password-form-input.component';
export * from './shared/dynamic-form-inputs/product-selector-form-input/product-selector-form-input.component';
export * from './shared/dynamic-form-inputs/register-dynamic-input-components';
export * from './shared/dynamic-form-inputs/select-form-input/select-form-input.component';
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/generated-shop-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export type Maybe<T> = T | null;

/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
ID: string | number;
String: string;
Boolean: boolean;
Int: number;
Expand Down
10 changes: 5 additions & 5 deletions packages/common/src/generated-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export type Maybe<T> = T | null;

/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
ID: string | number;
String: string;
Boolean: boolean;
Int: number;
Expand Down Expand Up @@ -606,7 +606,7 @@ export type CreateZoneInput = {
/**
* @description
* ISO 4217 currency code
*
*
* @docsCategory common
*/
export enum CurrencyCode {
Expand Down Expand Up @@ -1399,7 +1399,7 @@ export type JobSortParameter = {
/**
* @description
* The state of a Job in the JobQueue
*
*
* @docsCategory common
*/
export enum JobState {
Expand All @@ -1417,7 +1417,7 @@ export enum JobState {
* region or script modifier (e.g. de_AT). The selection available is based
* on the [Unicode CLDR summary list](https://unicode-org.github.io/cldr-staging/charts/37/summary/root.html)
* and includes the major spoken languages of the world and any widely-used variants.
*
*
* @docsCategory common
*/
export enum LanguageCode {
Expand Down Expand Up @@ -2621,7 +2621,7 @@ export type PaymentMethodSortParameter = {
* @description
* Permissions for administrators and customers. Used to control access to
* GraphQL resolvers via the {@link Allow} decorator.
*
*
* @docsCategory common
*/
export enum Permission {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/api/resolvers/base/base-auth.resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export class BaseAuthResolver {
*/
protected publiclyAccessibleUser(user: User): CurrentUser {
return {
id: user.id as string,
id: user.id,
identifier: user.identifier,
channels: getUserChannelsPermissions(user) as CurrentUserChannel[],
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class ShopCustomerResolver {
@Args() args: MutationCreateCustomerAddressArgs,
): Promise<Address> {
const customer = await this.getCustomerForOwner(ctx);
return this.customerService.createAddress(ctx, customer.id as string, args.input);
return this.customerService.createAddress(ctx, customer.id, args.input);
}

@Mutation()
Expand All @@ -59,7 +59,7 @@ export class ShopCustomerResolver {
): Promise<Address> {
const customer = await this.getCustomerForOwner(ctx);
const customerAddresses = await this.customerService.findAddressesByCustomerId(ctx, customer.id);
if (!customerAddresses.find((address) => idsAreEqual(address.id, args.input.id))) {
if (!customerAddresses.find(address => idsAreEqual(address.id, args.input.id))) {
throw new ForbiddenError();
}
return this.customerService.updateAddress(ctx, args.input);
Expand All @@ -73,7 +73,7 @@ export class ShopCustomerResolver {
): Promise<boolean> {
const customer = await this.getCustomerForOwner(ctx);
const customerAddresses = await this.customerService.findAddressesByCustomerId(ctx, customer.id);
if (!customerAddresses.find((address) => idsAreEqual(address.id, args.id))) {
if (!customerAddresses.find(address => idsAreEqual(address.id, args.id))) {
throw new ForbiddenError();
}
return this.customerService.deleteAddress(ctx, args.id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ export class ShopOrderResolver {
// to populate the initial default Address.
if (addresses.length === 0 && order.shippingAddress?.country) {
const address = order.shippingAddress;
await this.customerService.createAddress(ctx, order.customer.id as string, {
await this.customerService.createAddress(ctx, order.customer.id, {
...address,
streetLine1: address.streetLine1 || '',
streetLine2: address.streetLine2 || '',
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ export async function getAllEntities(userConfig: Partial<VendureConfig>): Promis
*/
function setExposedHeaders(config: Readonly<RuntimeVendureConfig>) {
if (config.authOptions.tokenMethod === 'bearer') {
const authTokenHeaderKey = config.authOptions.authTokenHeaderKey as string;
const authTokenHeaderKey = config.authOptions.authTokenHeaderKey;
const corsOptions = config.apiOptions.cors;
if (typeof corsOptions !== 'boolean') {
const { exposedHeaders } = corsOptions;
Expand Down
33 changes: 17 additions & 16 deletions packages/core/src/data-import/providers/importer/importer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { ImportInfo, LanguageCode } from '@vendure/common/lib/generated-types';
import { normalizeString } from '@vendure/common/lib/normalize-string';
import { ID } from '@vendure/common/lib/shared-types';
import ProgressBar from 'progress';
import { Observable } from 'rxjs';
import { Stream } from 'stream';
Expand Down Expand Up @@ -30,7 +31,7 @@ export type OnProgressFn = (progess: ImportProgress) => void;

@Injectable()
export class Importer {
private taxCategoryMatches: { [name: string]: string } = {};
private taxCategoryMatches: { [name: string]: ID } = {};
// These Maps are used to cache newly-created entities and prevent duplicates
// from being created.
private facetMap = new Map<string, Facet>();
Expand Down Expand Up @@ -148,8 +149,8 @@ export class Importer {
errors = errors.concat(createProductAssets.errors);
}
const createdProductId = await this.fastImporter.createProduct({
featuredAssetId: productAssets.length ? (productAssets[0].id as string) : undefined,
assetIds: productAssets.map(a => a.id) as string[],
featuredAssetId: productAssets.length ? productAssets[0].id : undefined,
assetIds: productAssets.map(a => a.id),
facetValueIds: await this.getFacetValueIds(product.facets, languageCode),
translations: [
{
Expand All @@ -162,7 +163,7 @@ export class Importer {
customFields: product.customFields,
});

const optionsMap: { [optionName: string]: string } = {};
const optionsMap: { [optionName: string]: ID } = {};
for (const optionGroup of product.optionGroups) {
const code = normalizeString(`${product.name}-${optionGroup.name}`, '-');
const groupId = await this.fastImporter.createProductOptionGroup({
Expand All @@ -177,7 +178,7 @@ export class Importer {
});
for (const option of optionGroup.values) {
const createdOptionId = await this.fastImporter.createProductOption({
productOptionGroupId: groupId as string,
productOptionGroupId: groupId,
code: normalizeString(option, '-'),
translations: [
{
Expand All @@ -186,7 +187,7 @@ export class Importer {
},
],
});
optionsMap[option] = createdOptionId as string;
optionsMap[option] = createdOptionId;
}
await this.fastImporter.addOptionGroupToProduct(createdProductId, groupId);
}
Expand All @@ -197,15 +198,15 @@ export class Importer {
if (createVariantAssets.errors.length) {
errors = errors.concat(createVariantAssets.errors);
}
let facetValueIds: string[] = [];
let facetValueIds: ID[] = [];
if (0 < variant.facets.length) {
facetValueIds = await this.getFacetValueIds(variant.facets, languageCode);
}
const createdVariant = await this.fastImporter.createProductVariant({
productId: createdProductId as string,
productId: createdProductId,
facetValueIds,
featuredAssetId: variantAssets.length ? (variantAssets[0].id as string) : undefined,
assetIds: variantAssets.map(a => a.id) as string[],
featuredAssetId: variantAssets.length ? variantAssets[0].id : undefined,
assetIds: variantAssets.map(a => a.id),
sku: variant.sku,
taxCategoryId: this.getMatchingTaxCategoryId(variant.taxCategory, taxCategories),
stockOnHand: variant.stockOnHand,
Expand Down Expand Up @@ -235,8 +236,8 @@ export class Importer {
private async getFacetValueIds(
facets: ParsedProductVariant['facets'],
languageCode: LanguageCode,
): Promise<string[]> {
const facetValueIds: string[] = [];
): Promise<ID[]> {
const facetValueIds: ID[] = [];

for (const item of facets) {
const facetName = item.facet;
Expand Down Expand Up @@ -277,7 +278,7 @@ export class Importer {
}
this.facetValueMap.set(facetValueMapKey, facetValueEntity);
}
facetValueIds.push(facetValueEntity.id as string);
facetValueIds.push(facetValueEntity.id);
}

return facetValueIds;
Expand All @@ -287,14 +288,14 @@ export class Importer {
* Attempts to match a TaxCategory entity against the name supplied in the import table. If no matches
* are found, the first TaxCategory id is returned.
*/
private getMatchingTaxCategoryId(name: string, taxCategories: TaxCategory[]): string {
private getMatchingTaxCategoryId(name: string, taxCategories: TaxCategory[]): ID {
if (this.taxCategoryMatches[name]) {
return this.taxCategoryMatches[name];
}
const regex = new RegExp(name, 'i');
const found = taxCategories.find(tc => !!tc.name.match(regex));
const match = found ? found : taxCategories[0];
this.taxCategoryMatches[name] = match.id as string;
return match.id as string;
this.taxCategoryMatches[name] = match.id;
return match.id;
}
}
12 changes: 6 additions & 6 deletions packages/core/src/data-import/providers/populator/populator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,9 @@ export class Populator {
`The defaultZone (${data.defaultZone}) did not match any zones from the InitialData`,
);
}
const defaultZoneId = defaultZone.entity.id as string;
const defaultZoneId = defaultZone.entity.id;
await this.channelService.update({
id: channel.id as string,
id: channel.id,
defaultTaxZoneId: defaultZoneId,
defaultShippingZoneId: defaultZoneId,
});
Expand All @@ -156,13 +156,13 @@ export class Populator {
zoneItem = { entity: zoneEntity, members: [] };
zones.set(zone, zoneItem);
}
zoneItem.members.push(countryEntity.id as string);
zoneItem.members.push(countryEntity.id);
}

// add the countries to the respective zones
for (const zoneItem of zones.values()) {
await this.zoneService.addMembersToZone(ctx, {
zoneId: zoneItem.entity.id as string,
zoneId: zoneItem.entity.id,
memberIds: zoneItem.members,
});
}
Expand All @@ -181,9 +181,9 @@ export class Populator {

for (const { entity } of zoneMap.values()) {
await this.taxRateService.create(ctx, {
zoneId: entity.id as string,
zoneId: entity.id,
value: taxRate.percentage,
categoryId: category.id as string,
categoryId: category.id,
name: `${taxRate.name} ${entity.name}`,
enabled: true,
});
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/data-import/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';

import { Zone } from '../entity/zone/zone.entity';

export type ZoneMap = Map<string, { entity: Zone; members: string[] }>;
export type ZoneMap = Map<string, { entity: Zone; members: ID[] }>;

export interface CountryDefinition {
code: string;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/job-queue/job-queue.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export class JobQueueService implements OnApplicationBootstrap, OnModuleDestroy
* Gets jobs by ids. The implementation is handled by the configured
* {@link JobQueueStrategy}.
*/
getJobsById(ids: string[]): Promise<Job[]> {
getJobsById(ids: ID[]): Promise<Job[]> {
return this.jobQueueStrategy.findManyById(ids);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export class AdministratorService {
password: superadminCredentials.password,
firstName: 'Super',
lastName: 'Admin',
roleIds: [superAdminRole.id as string],
roleIds: [superAdminRole.id],
});
}
}
Expand Down
18 changes: 7 additions & 11 deletions packages/core/src/service/services/customer.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ export class CustomerService {
.leftJoinAndSelect('country.translations', 'countryTranslation')
.where('address.customer = :id', { id: customerId })
.getMany()
.then((addresses) => {
addresses.forEach((address) => {
.then(addresses => {
addresses.forEach(address => {
address.country = translateDeep(address.country, ctx.languageCode);
});
return addresses;
Expand Down Expand Up @@ -168,7 +168,7 @@ export class CustomerService {
}
let user = await this.userService.getUserByEmailAddress(input.emailAddress);
const hasNativeAuthMethod = !!user?.authenticationMethods.find(
(m) => m instanceof NativeAuthenticationMethod,
m => m instanceof NativeAuthenticationMethod,
);
if (user && user.verified) {
if (hasNativeAuthMethod) {
Expand Down Expand Up @@ -413,11 +413,7 @@ export class CustomerService {
return this.connection.getRepository(Customer).save(customer);
}

async createAddress(
ctx: RequestContext,
customerId: string,
input: CreateAddressInput,
): Promise<Address> {
async createAddress(ctx: RequestContext, customerId: ID, input: CreateAddressInput): Promise<Address> {
const customer = await this.connection.manager.findOne(Customer, customerId, {
where: { deletedAt: null },
relations: ['addresses'],
Expand Down Expand Up @@ -542,8 +538,8 @@ export class CustomerService {
.findOne(addressId, { relations: ['customer', 'customer.addresses'] });
if (result) {
const customerAddressIds = result.customer.addresses
.map((a) => a.id)
.filter((id) => !idsAreEqual(id, addressId)) as string[];
.map(a => a.id)
.filter(id => !idsAreEqual(id, addressId)) as string[];

if (customerAddressIds.length) {
if (input.defaultBillingAddress === true) {
Expand Down Expand Up @@ -576,7 +572,7 @@ export class CustomerService {
const customerAddresses = result.customer.addresses;
if (1 < customerAddresses.length) {
const otherAddresses = customerAddresses
.filter((address) => !idsAreEqual(address.id, addressToDelete.id))
.filter(address => !idsAreEqual(address.id, addressToDelete.id))
.sort((a, b) => (a.id < b.id ? -1 : 1));
if (addressToDelete.defaultShippingAddress) {
otherAddresses[0].defaultShippingAddress = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class OrderTestingService {
const mockOrder = await this.buildMockOrder(ctx, input.shippingAddress, input.lines);
const eligibleMethods = await this.shippingCalculator.getEligibleShippingMethods(ctx, mockOrder);
return eligibleMethods.map(result => ({
id: result.method.id as string,
id: result.method.id,
price: result.result.price,
priceWithTax: result.result.priceWithTax,
description: result.method.description,
Expand Down
Loading

0 comments on commit dc7b303

Please sign in to comment.