Skip to content

Commit

Permalink
Decimal field updates (#6663)
Browse files Browse the repository at this point in the history
  • Loading branch information
emmatown authored Sep 28, 2021
1 parent afdce50 commit 480c875
Show file tree
Hide file tree
Showing 13 changed files with 458 additions and 118 deletions.
5 changes: 5 additions & 0 deletions .changeset/beige-cycles-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystone-next/keystone': major
---

In the `decimal` field, `defaultValue` is now a static number written as a string, `isRequired` has moved to `validation.isRequired` and now also requires the input isn't `NaN`, along with new `validation.min` and `validation.max` options. The `decimal` field can also be made non-nullable at the database-level with the `isNullable` option which defaults to `true`. `graphql.read.isNonNull` can also be set if the field has `isNullable: false` and you have no read access control and you don't intend to add any in the future, it will make the GraphQL output field non-nullable. `graphql.create.isNonNull` can also be set if you have no create access control and you don't intend to add any in the future, it will make the GraphQL create input field non-nullable.
29 changes: 23 additions & 6 deletions docs/pages/docs/apis/fields.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -299,16 +299,29 @@ A `decimal` field represents a decimal value.

Options:

- `defaultValue` (default: `undefined`): Can be either a decimal value or an async function which takes an argument `({ context, originalInput })` and returns a decimal value.
- `defaultValue` (default: `undefined`): Can be a decimal value written as a string
This value will be used for the field when creating items if no explicit value is set.
`context` is a [`KeystoneContext`](./context) object.
`originalInput` is an object containing the data passed in to the `create` mutation.
- `precision` (default: `18`): Maximum number of digits that are present in the number.
- `scale` (default: `4`): Maximum number of decimal places.
- `isRequired` (default: `false`): If `true` then this field can never be set to `null`.
- `isNullable` (default: `true`): If `false` then this field will be made non-nullable in the database and it will never be possible to set as `null`.
- `validation.isRequired` (default: `false`): If `true` then this field can never be set to `null`.
Unlike `isNullable`, this will require that a value is provided in the Admin UI.
It will also validate this when creating and updating an item through the GraphQL API but it will not enforce it at the database level.
If you would like to enforce it being non-null at the database-level and in the Admin UI, you can set both `isNullable: false` and `validation.isRequired: true`.
- `validation.min` (default: `undefined`): This describes the minimum number allowed. If you attempt to submit a number under this, you will get a validation error.
- `validation.max` (default: `undefined`): This describes the maximum number allowed. If you attempt to submit a number over this, you will get a validation error.
- If you want to specify a range within which the numbers must fall, specify both a minimum and a maximum value.
- `isIndexed` (default: `false`)
- If `true` then this field will be indexed by the database.
- If `'unique'` then all values of this field must be unique.
- `graphql.read.isNonNull` (default: `false`): If you have no read access control and you don't intend to add any in the future,
you can set this to true and the output field will be non-nullable. This is only allowed when you have no read access control because otherwise,
when access is denied, `null` will be returned which will cause an error since the field is non-nullable and the error
will propagate up until a nullable field is found which means the entire item will be unreadable and when doing an `items` query, all the items will be unreadable.
- `graphql.create.isNonNull` (default: `false`): If you have no create access control and you want to explicitly show that this is field is non-nullable in the create input
you can set this to true and the create field will be non-nullable and have a default value at the GraphQL level.
This is only allowed when you have no create access control because otherwise, the item will always fail access control
if a user doesn't have access to create the particular field regardless of whether or not they specify the field in the create.

```typescript
import { config, list } from '@keystone-next/keystone';
Expand All @@ -319,10 +332,14 @@ export default config({
ListName: list({
fields: {
fieldName: decimal({
defaultValue: 3.142,
defaultValue: '3.142',
precision: 12,
scale: 3,
isRequired: true,
validation: {
isRequired: true,
max: '10000',
min: '2',
},
isIndexed: 'unique',
}),
/* ... */
Expand Down
139 changes: 118 additions & 21 deletions packages/keystone/src/fields/types/decimal/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { humanize } from '../../../lib/utils';
import {
fieldType,
FieldTypeFunc,
Expand All @@ -6,26 +7,55 @@ import {
graphql,
orderDirectionEnum,
Decimal,
FieldDefaultValue,
filters,
FieldData,
} from '../../../types';
import { resolveView } from '../../resolve-view';
import { assertCreateIsNonNullAllowed, assertReadIsNonNullAllowed } from '../../non-null-graphql';

export type DecimalFieldConfig<TGeneratedListTypes extends BaseGeneratedListTypes> =
CommonFieldConfig<TGeneratedListTypes> & {
isRequired?: boolean;
validation?: {
min?: string;
max?: string;
isRequired?: boolean;
};
precision?: number;
scale?: number;
defaultValue?: FieldDefaultValue<string, TGeneratedListTypes>;
defaultValue?: string;
isIndexed?: boolean | 'unique';
};
graphql?: { create?: { isNonNull?: boolean } };
} & (
| { isNullable?: true }
| {
isNullable: false;
graphql?: { read?: { isNonNull?: boolean } };
}
);

function parseDecimalValueOption(meta: FieldData, value: string, name: string) {
let decimal: Decimal;
try {
decimal = new Decimal(value);
} catch (err) {
throw new Error(
`The decimal field at ${meta.listKey}.${meta.fieldKey} specifies ${name}: ${value}, this is not valid decimal value.`
);
}
if (!decimal.isFinite()) {
throw new Error(
`The decimal field at ${meta.listKey}.${meta.fieldKey} specifies ${name}: ${value} which is not finite but ${name} must be finite.`
);
}
return decimal;
}

export const decimal =
<TGeneratedListTypes extends BaseGeneratedListTypes>({
isIndexed,
precision = 18,
scale = 4,
isRequired,
validation,
defaultValue,
...config
}: DecimalFieldConfig<TGeneratedListTypes> = {}): FieldTypeFunc =>
Expand Down Expand Up @@ -53,49 +83,116 @@ export const decimal =
);
}

const fieldLabel = config.label ?? humanize(meta.fieldKey);

const max =
validation?.max === undefined
? undefined
: parseDecimalValueOption(meta, validation.max, 'validation.max');
const min =
validation?.max === undefined
? undefined
: parseDecimalValueOption(meta, validation.max, 'validation.max');

if (min !== undefined && max !== undefined && max.lessThan(min)) {
throw new Error(
`The decimal field at ${meta.listKey}.${meta.fieldKey} specifies a validation.max that is less than the validation.min, and therefore has no valid options`
);
}

const parsedDefaultValue =
defaultValue === undefined
? undefined
: parseDecimalValueOption(meta, defaultValue, 'defaultValue');

if (config.isNullable === false) {
assertReadIsNonNullAllowed(meta, config);
}
assertCreateIsNonNullAllowed(meta, config);

const mode = config.isNullable === false ? 'required' : 'optional';

const index = isIndexed === true ? 'index' : isIndexed || undefined;
const dbField = {
kind: 'scalar',
mode: 'optional',
mode,
scalar: 'Decimal',
nativeType: `Decimal(${precision}, ${scale})`,
index,
default:
defaultValue === undefined ? undefined : { kind: 'literal' as const, value: defaultValue },
} as const;
return fieldType(dbField)({
...config,
hooks: {
...config.hooks,
async validateInput(args) {
const val: Decimal | null | undefined = args.resolvedData[meta.fieldKey];

if (val === null && validation?.isRequired) {
args.addValidationError(`${fieldLabel} is required`);
}
if (val != null) {
if (min !== undefined && val.lessThan(min)) {
args.addValidationError(`${fieldLabel} must be greater than or equal to ${min}`);
}

if (max !== undefined && val.greaterThan(max)) {
args.addValidationError(`${fieldLabel} must be less than or equal to ${max}`);
}
}

await config.hooks?.validateInput?.(args);
},
},
input: {
where: {
arg: graphql.arg({ type: filters[meta.provider].Decimal.optional }),
resolve: filters.resolveCommon,
arg: graphql.arg({ type: filters[meta.provider].Decimal[mode] }),
resolve: mode === 'optional' ? filters.resolveCommon : undefined,
},
create: {
arg: graphql.arg({ type: graphql.String }),
arg: graphql.arg({
type: config.graphql?.create?.isNonNull
? graphql.nonNull(graphql.Decimal)
: graphql.Decimal,
defaultValue: config.graphql?.create?.isNonNull ? parsedDefaultValue : undefined,
}),
resolve(val) {
if (val == null) return val;
return new Decimal(val);
if (val === undefined) {
return parsedDefaultValue ?? null;
}
return val;
},
},
update: {
arg: graphql.arg({ type: graphql.String }),
resolve(val) {
if (val == null) return val;
return new Decimal(val);
},
arg: graphql.arg({ type: graphql.Decimal }),
},
orderBy: { arg: graphql.arg({ type: orderDirectionEnum }) },
},
output: graphql.field({
type: graphql.String,
type:
config.isNullable === false && config.graphql?.read?.isNonNull
? graphql.nonNull(graphql.Decimal)
: graphql.Decimal,
resolve({ value }) {
if (value === null) return null;
return value.toFixed(scale);
if (value === null) {
return null;
}
const val: Decimal & { scaleToPrint?: number } = new Decimal(value);
val.scaleToPrint = scale;
return val;
},
}),
views: resolveView('decimal/views'),
getAdminMeta: () => ({
getAdminMeta: (): import('./views').DecimalFieldMeta => ({
defaultValue: defaultValue ?? null,
precision,
scale,
validation: {
isRequired: validation?.isRequired ?? false,
max: validation?.max ?? null,
min: validation?.min ?? null,
},
}),
__legacy: { isRequired, defaultValue },
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { decimal } from '../..';

export const name = 'Decimal with isNullable: false';
export const typeFunction = (x: any) => decimal({ isNullable: false, ...x });
export const exampleValue = () => '6.28';
export const exampleValue2 = () => '6.45';
export const supportsGraphQLIsNonNull = true;
export const supportsUnique = true;
export const skipRequiredTest = true;
export const fieldName = 'price';
export const unSupportedAdapterList = ['sqlite'];

export const getTestFields = () => ({
price: decimal({ scale: 2, isFilterable: true, isNullable: false }),
});

export const initItems = () => {
return [
{ name: 'price1', price: '-123.45' },
{ name: 'price2', price: '0.01' },
{ name: 'price3', price: '50.00' },
{ name: 'price4', price: '2000.00' },
{ name: 'price5', price: '40000.00' },
{ name: 'price6', price: '1.00' },
{ name: 'price7', price: '2.00' },
];
};

export const storedValues = () => [
{ name: 'price1', price: '-123.45' },
{ name: 'price2', price: '0.01' },
{ name: 'price3', price: '50.00' },
{ name: 'price4', price: '2000.00' },
{ name: 'price5', price: '40000.00' },
{ name: 'price6', price: '1.00' },
{ name: 'price7', price: '2.00' },
];

export const supportedFilters = () => [];
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const typeFunction = decimal;
export const exampleValue = () => '6.28';
export const exampleValue2 = () => '6.45';
export const supportsUnique = true;
export const skipRequiredTest = true;
export const fieldName = 'price';
export const unSupportedAdapterList = ['sqlite'];

Expand Down
Loading

0 comments on commit 480c875

Please sign in to comment.