Skip to content

Commit

Permalink
fix(imports): self references (#23)
Browse files Browse the repository at this point in the history
When a type references itself in one of the fields, no self referencing imports should be added.

Fixes #19
  • Loading branch information
marcolink authored Sep 10, 2020
1 parent fb4dcec commit 1be9c35
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 4 deletions.
3 changes: 2 additions & 1 deletion src/cf-definitions-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@ export default class CFDefinitionsBuilder {
moduleSpecifier: '@contentful/rich-text-types',
namespaceImport: 'CFRichTextTypes',
});
file.addImportDeclarations(propertyImports(field));

file.addImportDeclarations(propertyImports(field, file.getBaseNameWithoutExtension()));
};

private mergeFile = (mergeFileName = 'ContentTypes'): SourceFile => {
Expand Down
12 changes: 9 additions & 3 deletions src/cf-property-imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,18 @@ const moduleImport = (module: string) => ({
],
});

export const propertyImports = (field: Field): OptionalKind<ImportDeclarationStructure>[] => {
export const propertyImports = (field: Field, ignoreModule?: string): OptionalKind<ImportDeclarationStructure>[] => {
const filterIgnoredModule = (name: string) => ignoreModule !== moduleName(name);

if (field.type === 'Link' && field.linkType === 'Entry') {
return linkContentTypeValidations(field).map(moduleImport);
return linkContentTypeValidations(field)
.filter(filterIgnoredModule)
.map(moduleImport);
}
if (field.type === 'Array' && field.items) {
return linkContentTypeValidations(field.items).map(moduleImport);
return linkContentTypeValidations(field.items)
.filter(filterIgnoredModule)
.map(moduleImport);
}
return [];
};
44 changes: 44 additions & 0 deletions test/cf-definitions-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,4 +402,48 @@ describe('A Contentful definitions builder', () => {
export { TypeSysId, TypeSysIdFields } from "./TypeSysId";
`));
});

it('can self-reference', async () => {
builder.appendType(modelType);
builder.appendType({
id: 'rootId',
name: 'Root Name',
sys: {
id: 'myType',
type: 'ContentType',
}, fields: [
{
id: 'linkFieldId',
name: 'Linked entry Field',
type: 'Link',
localized: false,
required: false,
validations: [
{
linkContentType: [
'myType',
],
},
],
disabled: false,
omitted: false,
linkType: 'Entry',
},
],
});

await builder.write(fixturesPath);

const result2 = await fs.readFile(path.resolve(fixturesPath, 'TypeMyType.ts'));

expect('\n' + result2.toString()).to.equal(stripIndent(`
import * as Contentful from "contentful";
export interface TypeMyTypeFields {
linkFieldId?: Contentful.Entry<TypeMyTypeFields>;
}
export type TypeMyType = Contentful.Entry<TypeMyTypeFields>;
`));
});
});

0 comments on commit 1be9c35

Please sign in to comment.