Skip to content

Commit

Permalink
fix(enums): fixes to support unique enums (#84)
Browse files Browse the repository at this point in the history
* reproduce issue with adding enum to Unique

* fixes to support unique enums
  • Loading branch information
goldcaddy77 authored Apr 12, 2019
1 parent 79cd58e commit 9a028f7
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 24 deletions.
4 changes: 3 additions & 1 deletion examples/2-complex-example/src/modules/user/user.model.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Authorized } from 'type-graphql';

import { Unique } from 'typeorm';
import { BaseModel, EmailField, EnumField, Model, StringField } from '../../../../../src';

// Note: this must be exported and in the same file where it's attached with @EnumField
Expand All @@ -10,14 +11,15 @@ export enum StringEnum {
}

@Model()
@Unique(['firstName', 'stringEnumField'])
export class User extends BaseModel {
@StringField({ maxLength: 30 })
firstName?: string;

@StringField({ maxLength: 50, minLength: 2 })
lastName?: string;

@EnumField('StringEnum', StringEnum, { nullable: true })
@EnumField('StringEnum', StringEnum)
stringEnumField?: StringEnum;

@EmailField()
Expand Down
13 changes: 10 additions & 3 deletions examples/2-complex-example/tools/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,16 @@ const logger = Debug('warthog:seed');
const NUM_USERS = 100;

async function seedDatabase() {
const server = getServer();
const server = getServer({ introspection: true });
await server.start();

const binding = await server.getBinding();
let binding;
try {
binding = await server.getBinding();
} catch (error) {
console.error(error);
return process.exit(1);
}

for (let index = 0; index < NUM_USERS; index++) {
const random = new Date()
Expand All @@ -34,7 +40,8 @@ async function seedDatabase() {
data: {
email,
firstName,
lastName
lastName,
stringEnumField: 'FOO'
}
},
`{ id email createdAt createdById }`
Expand Down
21 changes: 16 additions & 5 deletions src/core/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,20 @@ export class Server<C extends BaseContext> {
}

async getBinding(options: { origin?: string; token?: string } = {}): Promise<Binding> {
return getRemoteBinding(`http://${this.appHost}:${this.appPort}/graphql`, {
origin: 'warthog',
...options
});
let binding;
try {
binding = await getRemoteBinding(`http://${this.appHost}:${this.appPort}/graphql`, {
origin: 'warthog',
...options
});
return binding;
} catch (error) {
if (error.result && error.result.errors) {
const messages = error.result.errors.map((item: any) => item.message);
throw new Error(JSON.stringify(messages));
}
throw error;
}
}

async buildGraphQLSchema(): Promise<GraphQLSchema> {
Expand Down Expand Up @@ -189,7 +199,7 @@ export class Server<C extends BaseContext> {
},
request: options.req,
// Allows consumer to add to the context object - ex. context.user
...consumerCtx,
...consumerCtx
};
},
introspection: this.introspection,
Expand All @@ -206,6 +216,7 @@ export class Server<C extends BaseContext> {
debug('start:applyMiddleware:end');

const url = `http://${this.appHost}:${this.appPort}${this.graphQLServer.graphqlPath}`;
debug(`url: ${url}`);

this.httpServer = app.listen({ port: this.appPort }, () =>
this.logger.info(`🚀 Server ready at ${url}`)
Expand Down
32 changes: 17 additions & 15 deletions src/schema/TypeORMConverter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,15 +105,15 @@ export function entityToCreateInput(entity: EntityMetadata): string {
!column.isVersion &&
!SYSTEM_FIELDS.includes(column.propertyName)
) {
const graphQLType = columnToGraphQLType(column);
const graphQLDataType = columnTypeToGraphQLDataType(column);
const nullable = column.isNullable ? '{ nullable: true }' : '';
const tsRequired = column.isNullable ? '?' : '!';
const tsType = columnToTypeScriptType(column);

if (column.enum) {
fieldTemplates += `
@TypeGraphQLField(type => ${graphQLType}, ${nullable})
${column.propertyName}${tsRequired}: ${graphQLType};
@TypeGraphQLField(type => ${graphQLDataType}, ${nullable})
${column.propertyName}${tsRequired}: ${graphQLDataType};
`;
} else {
fieldTemplates += `
Expand Down Expand Up @@ -146,13 +146,13 @@ export function entityToUpdateInput(entity: EntityMetadata): string {
) {
// TODO: also don't allow updated foreign key fields
// Example: photo.userId: String
const graphQLType = columnToGraphQLType(column);
const graphQLDataType = columnTypeToGraphQLDataType(column);
const tsType = columnToTypeScriptType(column);

if (column.enum) {
fieldTemplates += `
@TypeGraphQLField(type => ${graphQLType}, { nullable: true })
${column.propertyName}?: ${graphQLType};
@TypeGraphQLField(type => ${graphQLDataType}, { nullable: true })
${column.propertyName}?: ${graphQLDataType};
`;
} else {
fieldTemplates += `
Expand Down Expand Up @@ -200,14 +200,16 @@ export function entityToWhereInput(entity: EntityMetadata): string {

const { graphqlType, tsType } = columnToTypes(column);

const graphQLDataType = columnTypeToGraphQLDataType(column);

// TODO: for foreign key fields, only allow the same filters as ID below
// Example: photo.userId: String
if (column.isPrimary || graphqlType === GraphQLID) {
fieldTemplates += `
@TypeGraphQLField(type => ${graphqlType},{ nullable: true })
@TypeGraphQLField(type => ${graphQLDataType},{ nullable: true })
${column.propertyName}_eq?: string;
@TypeGraphQLField(type => [${graphqlType}], { nullable: true })
@TypeGraphQLField(type => [${graphQLDataType}], { nullable: true })
${column.propertyName}_in?: string[];
`;
} else if (graphqlType === GraphQLString) {
Expand All @@ -226,7 +228,7 @@ export function entityToWhereInput(entity: EntityMetadata): string {
@TypeGraphQLField({ nullable: true })
${column.propertyName}_endsWith?: ${tsType};
@TypeGraphQLField(type => [${graphqlType}], { nullable: true })
@TypeGraphQLField(type => [${graphQLDataType}], { nullable: true })
${column.propertyName}_in?: ${tsType}[];
`;
} else if (graphqlType === GraphQLFloat || graphqlType === GraphQLInt) {
Expand All @@ -246,7 +248,7 @@ export function entityToWhereInput(entity: EntityMetadata): string {
@TypeGraphQLField({ nullable: true })
${column.propertyName}_lte?: ${tsType};
@TypeGraphQLField(type => [${graphqlType}], { nullable: true })
@TypeGraphQLField(type => [${graphQLDataType}], { nullable: true })
${column.propertyName}_in?: ${tsType}[];
`;
} else if (graphqlType === GraphQLISODateTime) {
Expand All @@ -266,11 +268,11 @@ export function entityToWhereInput(entity: EntityMetadata): string {
} else {
// Enums will fall through here
fieldTemplates += `
@TypeGraphQLField(type => ${graphqlType}, { nullable: true })
${column.propertyName}_eq?: ${graphqlType};
@TypeGraphQLField(type => ${graphQLDataType}, { nullable: true })
${column.propertyName}_eq?: ${graphQLDataType};
@TypeGraphQLField(type => [${graphqlType}], { nullable: true })
${column.propertyName}_in?: ${graphqlType}[];
@TypeGraphQLField(type => [${graphQLDataType}], { nullable: true })
${column.propertyName}_in?: ${graphQLDataType}[];
`;
}
});
Expand Down Expand Up @@ -363,7 +365,7 @@ export function columnToGraphQLType(column: ColumnMetadata): GraphQLScalarType |
// Check to see if this column is an enum and return that
const enumObject = getMetadataStorage().getEnum(column.entityMetadata.name, column.propertyName);
if (enumObject) {
return enumObject.name;
return enumObject;
} else if (column.propertyName.match(/Id$/)) {
return GraphQLID;
}
Expand Down

0 comments on commit 9a028f7

Please sign in to comment.