Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return meta data for Select field from GraphQL API #2679

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .changeset/thin-eels-train.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
'@keystonejs/api-tests': minor
'@keystonejs/keystone': minor
---

Exposes `dataType` and `options` meta data for `Select` fields:
```graphql
query {
_UserMeta {
schema {
fields {
name
type
...on _SelectMeta {
dataType
options {
label
}
}
}
}
}
}
```
8 changes: 8 additions & 0 deletions api-tests/fields.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ describe('Fields', () => {
test.todo('CRUD operations - tests missing');
}

if (mod.metaTests) {
describe(`Meta query`, () => {
mod.metaTests(keystoneTestWrapper);
});
} else {
test.todo('Meta query - tests missing');
}

if (mod.filterTests) {
describe(`Filtering`, () => {
mod.filterTests(keystoneTestWrapper);
Expand Down
22 changes: 21 additions & 1 deletion packages/fields/src/Implementation.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class Field {
constructor(
path,
{ hooks = {}, isRequired, defaultValue, access, label, schemaDoc, adminDoc, ...config },
{ getListByKey, listKey, listAdapter, fieldAdapterClass, defaultAccess, schemaNames }
{ getListByKey, listKey, listAdapter, fieldAdapterClass, defaultAccess, schemaNames, type }
) {
this.path = path;
this.isPrimaryKey = path === 'id';
Expand All @@ -27,6 +27,8 @@ class Field {
getListByKey,
{ ...config }
);
this.type = type;
this.gqlMetaType = `_${type.type}Meta`;

// Should be overwritten by types that implement a Relationship interface
this.isRelationship = false;
Expand Down Expand Up @@ -83,6 +85,24 @@ class Field {
return {};
}

getGqlMetaTypes({ interfaceType }) {
return [
`
type ${this.gqlMetaType} implements ${interfaceType} {
name: String
type: String
}
`,
];
}
gqlMetaQueryResolver() {
return {
__typename: this.gqlMetaType,
name: this.path,
type: this.type.type,
};
}

/*
* @param {Object} data
* @param {Object} data.resolvedData The incoming item for the mutation with
Expand Down
6 changes: 5 additions & 1 deletion packages/fields/src/types/OEmbed/Implementation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ const newOEmbed = ({ config = {} } = {}) => {
return new OEmbed(
path,
{ access: true, ...config },
{ listAdapter: { newFieldAdapter: () => {} }, schemaNames: ['public'] }
{
listAdapter: { newFieldAdapter: () => {} },
schemaNames: ['public'],
type: { type: 'OEmebed' },
}
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ function createRelationship({ path, config = {}, getListByKey = () => new MockLi
fieldAdapterClass: MockFieldAdapter,
defaultAccess: true,
schemaNames: ['public'],
type: { type: 'Relationship' },
});
}

Expand Down
68 changes: 68 additions & 0 deletions packages/fields/src/types/Select/Implementation.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import inflection from 'inflection';
import { Implementation } from '../../Implementation';
import { MongooseFieldAdapter } from '@keystonejs/adapter-mongoose';
import { KnexFieldAdapter } from '@keystonejs/adapter-knex';
import { upcase } from '@keystonejs/utils';

function initOptions(options) {
let optionsArray = options;
Expand All @@ -15,6 +16,14 @@ function initOptions(options) {
const VALID_DATA_TYPES = ['enum', 'string', 'integer'];
const DOCS_URL = 'https://keystonejs.com/keystonejs/fields/src/types/select/';

function dataTypeToGqlMetaType({ gqlMetaType, dataType }) {
return `${gqlMetaType}Type${upcase(dataType)}`;
}

function dataTypeToGqlValueField({ dataType }) {
return `${dataType.toLowerCase()}Value`;
}

function validateOptions({ options, dataType, listKey, path }) {
if (!VALID_DATA_TYPES.includes(dataType)) {
throw new Error(
Expand Down Expand Up @@ -97,6 +106,65 @@ export class Select extends Implementation {
]
: [];
}
getGqlMetaTypes({ interfaceType }) {
const { gqlMetaType } = this;
const dataTypeEnum = `${this.gqlMetaType}DataType`;
const optionsType = `${this.gqlMetaType}Options`;
const dataTypeToValueType = {
enum: 'String',
string: 'String',
integer: 'Int',
};
return [
`
enum ${dataTypeEnum} {
${VALID_DATA_TYPES.map(type => type.toUpperCase()).join('\n')}
}
`,
`
interface ${optionsType} {
label: String
}
`,
...VALID_DATA_TYPES.map(dataType => {
return `
type ${dataTypeToGqlMetaType({ gqlMetaType, dataType })} implements ${optionsType} {
label: String
${dataTypeToGqlValueField({ dataType })}: ${dataTypeToValueType[dataType]}
}
`;
}),
`
type ${this.gqlMetaType} implements ${interfaceType} {
name: String
type: String
dataType: ${dataTypeEnum}
options: [${optionsType}]
}
`,
];
}
gqlMetaQueryResolver() {
const { gqlMetaType, dataType } = this;
return {
...super.gqlMetaQueryResolver(),
dataType: this.dataType.toUpperCase(),
options: this.options.map(({ value, label }) => ({
__typename: dataTypeToGqlMetaType({ gqlMetaType, dataType }),
[dataTypeToGqlValueField({ dataType })]: value,
label,
})),
};
}
gqlAuxFieldResolvers() {
return {
// We have to implement this to avoid Apollo throwing a warning about it
// missing (even though it works just fine without it, grrrr)
[`${this.gqlMetaType}Options`]: {
__resolveType: ({ __typename }) => __typename,
},
};
}

extendAdminMeta(meta) {
const { options, dataType } = this;
Expand Down
92 changes: 91 additions & 1 deletion packages/fields/src/types/Select/test-fixtures.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { matchFilter } from '@keystonejs/test-utils';
import { matchFilter, graphqlRequest } from '@keystonejs/test-utils';
import Select from './';
import Text from '../Text';

Expand Down Expand Up @@ -264,3 +264,93 @@ export const filterTests = withKeystone => {
)
);
};

export const metaTests = withKeystone => {
const queryListMeta = async ({ keystone, listName }) => {
const list = keystone.getListByKey(listName);
const { listMetaName } = list.gqlNames;
const { data: { [listMetaName]: items } = {}, errors } = await graphqlRequest({
keystone,
query: `query {
${listMetaName} {
schema {
fields {
__typename
name
type
...on _SelectMeta {
dataType
options {
label
...on _SelectMetaTypeEnum {
enumValue
}
...on _SelectMetaTypeString {
stringValue
}
...on _SelectMetaTypeInteger {
integerValue
}
}
}
}
}
}
}`,
});
expect(errors).toBe(undefined);
return items;
};

test(
'includes all expected fields',
withKeystone(async ({ keystone, listName }) => {
const items = await queryListMeta({ keystone, listName });
expect(items).toEqual({
schema: {
fields: [
{
__typename: '_TextMeta',
name: 'name',
type: 'Text',
},
{
__typename: '_SelectMeta',
name: 'company',
type: 'Select',
dataType: 'ENUM',
options: [
{ label: 'Thinkmill', enumValue: 'thinkmill' },
{ label: 'Atlassian', enumValue: 'atlassian' },
{ label: 'Thomas Walker Gelato', enumValue: 'gelato' },
{ label: 'Cete, or Seat, or Attend ¯\\_(ツ)_/¯', enumValue: 'cete' },
],
},
{
__typename: '_SelectMeta',
name: 'selectString',
type: 'Select',
dataType: 'STRING',
options: [
{ label: 'A string', stringValue: 'a string' },
{ label: '1number', stringValue: '1number' },
{ label: '@¯\\_(ツ)_/¯', stringValue: '@¯\\_(ツ)_/¯' },
],
},
{
__typename: '_SelectMeta',
name: 'selectNumber',
type: 'Select',
dataType: 'INTEGER',
options: [
{ label: 'One', integerValue: 1 },
{ label: 'Two', integerValue: 2 },
{ label: 'Three', integerValue: 3 },
],
},
],
},
});
})
);
};
2 changes: 2 additions & 0 deletions packages/fields/tests/Implementation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const args = {
},
defaultAccess: true,
schemaNames: ['public'],
type: { type: 'AType' },
};

describe('new Implementation()', () => {
Expand All @@ -23,6 +24,7 @@ describe('new Implementation()', () => {
},
defaultAccess: true,
schemaNames: ['public'],
type: { type: 'AType' },
}
);
expect(impl).not.toBeNull();
Expand Down
1 change: 1 addition & 0 deletions packages/keystone/lib/List/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ module.exports = class List {
defaultAccess: this.defaultAccess.field,
createAuxList: this.createAuxList,
schemaNames: this._schemaNames,
type,
})
);
this.fields = Object.values(this.fieldsByPath);
Expand Down
Loading