Skip to content

Commit

Permalink
fix(one-to-many): one to manys should not be nullable (#479)
Browse files Browse the repository at this point in the history
  • Loading branch information
goldcaddy77 committed Jan 1, 2022
1 parent bc76172 commit 5d93245
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 17 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"debug": "^4.1.1",
"execa": "^4.0.3",
"express": "^4.17.1",
"flatted": "^3.2.4",
"gluegun": "^4.1.0",
"graphql": "^14.5.8",
"graphql-binding": "^2.5.2",
Expand Down
40 changes: 32 additions & 8 deletions src/core/BaseService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,20 @@ export class BaseService<E extends Node> {
orderBy?: string,
limit?: number,
offset?: number,
fields?: string[]
fields?: string[],
userId?: string,
options?: BaseOptionsExtended
): Promise<E[]> {
const manager = this.extractManager(options);

const DEFAULT_LIMIT = 50;
return this.buildFindQuery(
where as WhereExpression,
orderBy,
{ limit: limit || DEFAULT_LIMIT, offset },
fields
fields,
userId,
{ manager }
).getMany();
}

Expand All @@ -162,8 +168,12 @@ export class BaseService<E extends Node> {
whereUserInput: any = {}, // V3: WhereExpression = {},
orderBy?: string | string[],
_pageOptions: RelayPageOptionsInput = {},
fields?: ConnectionInputFields
fields?: ConnectionInputFields,
userId?: string, // Allow this param so that when we overload we can pass the userId for filtering data to user's "world"
options?: BaseOptionsExtended
): Promise<ConnectionResult<E>> {
const manager = this.extractManager(options);

// TODO: if the orderby items aren't included in `fields`, should we automatically include?
// TODO: FEATURE - make the default limit configurable
const DEFAULT_LIMIT = 50;
Expand Down Expand Up @@ -202,7 +212,9 @@ export class BaseService<E extends Node> {
whereCombined,
this.relayService.effectiveOrderStrings(sorts, relayPageOptions),
{ limit: limit + 1 }, // We ask for 1 too many so that we know if there is an additional page
requestedFields.selectFields
requestedFields.selectFields,
userId,
{ manager }
);

let rawData;
Expand Down Expand Up @@ -235,10 +247,14 @@ export class BaseService<E extends Node> {
where: any = {}, // W | WhereExpression
orderBy?: string | string[],
pageOptions?: LimitOffset,
fields?: string[]
fields?: string[],
userId?: string, // Allow this param so that when we overload we can pass the userId for filtering data to user's "world"
options?: BaseOptionsExtended
): SelectQueryBuilder<E> {
const manager = this.extractManager(options);

const DEFAULT_LIMIT = 50;
let qb = this.manager.createQueryBuilder<E>(this.entityClass, this.klass);
let qb = manager.createQueryBuilder<E>(this.entityClass, this.klass);
if (!pageOptions) {
pageOptions = {
limit: DEFAULT_LIMIT
Expand Down Expand Up @@ -393,8 +409,16 @@ export class BaseService<E extends Node> {
return qb;
}

async findOne<W>(where: W): Promise<E> {
const items = await this.find(where as any);
async findOne<W>(where: W, userId?: string, options?: BaseOptionsExtended): Promise<E> {
const items = await this.find(
where as any,
undefined,
undefined,
undefined,
undefined,
userId,
options
);
if (!items.length) {
throw new Error(`Unable to find ${this.entityClass.name} where ${JSON.stringify(where)}`);
} else if (items.length > 1) {
Expand Down
3 changes: 1 addition & 2 deletions src/decorators/OneToMany.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { Field } from 'type-graphql';
import { OneToMany as TypeORMOneToMany } from 'typeorm';

import { composeMethodDecorators, MethodDecoratorFactory } from '../utils';

export function OneToMany(parentType: any, joinFunc: any, options: any = {}): any {
const factories = [
Field(parentType, { nullable: true, ...options }) as MethodDecoratorFactory,
Field(parentType, { ...options }) as MethodDecoratorFactory,
TypeORMOneToMany(parentType, joinFunc) as MethodDecoratorFactory
];

Expand Down
5 changes: 3 additions & 2 deletions src/decorators/debug.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as Debug from 'debug';
import { stringify } from 'flatted';
import { performance } from 'perf_hooks';
import * as util from 'util';

Expand All @@ -12,7 +13,7 @@ export function debug(key: string): MethodDecorator {

if (util.types.isAsyncFunction(originalMethod)) {
descriptor.value = async function(...args: unknown[]): Promise<any> {
logger(`Entering ${propertyKey} with args: ${JSON.stringify(args)}`);
logger(`Entering ${propertyKey} with args: ${stringify(args)}`);
const start = performance.now();
const result = await originalMethod.apply(this, args);
const end = performance.now();
Expand All @@ -21,7 +22,7 @@ export function debug(key: string): MethodDecorator {
};
} else {
descriptor.value = function(...args: unknown[]) {
logger(`Entering ${propertyKey} with args: ${JSON.stringify(args)}`);
logger(`Entering ${propertyKey} with args: ${stringify(args)}`);
const start = performance.now();
const result = originalMethod.apply(this, args);
const end = performance.now();
Expand Down
2 changes: 1 addition & 1 deletion src/test/functional/__snapshots__/schema.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ type KitchenSink {
jsonField: JSONObject
idField: ID
stringEnumField: StringEnum
dishes: [Dish!]
dishes: [Dish!]!
numericField: Float
numericFieldCustomPrecisionScale: Float
noFilterField: String
Expand Down
2 changes: 1 addition & 1 deletion src/test/generated/binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ export interface KitchenSink {
jsonField?: JSONObject | null
idField?: ID_Output | null
stringEnumField?: StringEnum | null
dishes?: Array<Dish> | null
dishes: Array<Dish>
numericField?: Float | null
numericFieldCustomPrecisionScale?: Float | null
noFilterField?: String | null
Expand Down
2 changes: 1 addition & 1 deletion src/test/generated/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ type KitchenSink {
jsonField: JSONObject
idField: ID
stringEnumField: StringEnum
dishes: [Dish!]
dishes: [Dish!]!
numericField: Float
numericFieldCustomPrecisionScale: Float
noFilterField: String
Expand Down
5 changes: 3 additions & 2 deletions src/test/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { stringify } from 'flatted';
import { GraphQLError } from 'graphql';
import { getBindingError } from '../';

Expand Down Expand Up @@ -78,9 +79,9 @@ function toErrorString(obj: unknown, msg: string): string {
if (typeof obj === 'string') {
error = `${msg}: ${obj}`;
} else {
error = `${msg}: ${JSON.stringify(obj)}`;
error = `${msg}: ${stringify(obj)}`;
}

console.dir(obj);
console.error();
return error;
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3790,6 +3790,11 @@ flatted@^2.0.0:
resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.1.tgz#69e57caa8f0eacbc281d2e2cb458d46fdb449e08"
integrity sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg==

flatted@^3.2.4:
version "3.2.4"
resolved "https://registry.npmjs.org/flatted/-/flatted-3.2.4.tgz#28d9969ea90661b5134259f312ab6aa7929ac5e2"
integrity sha512-8/sOawo8tJ4QOBX8YlQBMxL8+RLZfxMQOif9o0KUKTNTjMYElWPE0r/m5VNFxTRd0NSw8qSy8dajrwX4RYI1Hw==

flush-write-stream@^1.0.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/flush-write-stream/-/flush-write-stream-1.1.1.tgz#8dd7d873a1babc207d94ead0c2e0e44276ebf2e8"
Expand Down

0 comments on commit 5d93245

Please sign in to comment.