Skip to content

Commit

Permalink
Add generator.assignments as a valid "findBy" source
Browse files Browse the repository at this point in the history
  • Loading branch information
MrLeebo committed Feb 25, 2024
1 parent 5c9c838 commit b69da60
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/finder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ export type ByTypeSourceObject =
| schema.Enumerator
| schema.Field
| schema.Property
| schema.Attribute;
| schema.Attribute
| schema.Assignment;

export type ByTypeMatchObject = Exclude<
ByTypeSourceObject,
Expand Down Expand Up @@ -38,16 +39,26 @@ export const findAllByType = <const Match extends ByTypeMatch>(
return list.filter(findBy(typeToMatch, options));
};

type NameOf<Match extends ByTypeMatch> = Extract<
Match,
Match extends 'assignment' ? 'key' : 'name'
>;

const findBy =
<Match extends ByTypeMatch>(
<Match extends ByTypeMatch, MatchName extends NameOf<Match>>(
typeToMatch: Match,
{ name }: ByTypeOptions = {}
) =>
(block: ByTypeSourceObject): block is FindByBlock<Match> => {
if (name != null) {
if (!('name' in block)) return false;
const nameAttribute = (
typeToMatch === 'assignment' ? 'key' : 'name'
) as MatchName;
if (!(nameAttribute in block)) return false;
const nameMatches =
typeof name === 'string' ? block.name === name : name.test(block.name);
typeof name === 'string'
? block[nameAttribute] === name
: name.test(block[nameAttribute]);
if (!nameMatches) return false;
}

Expand Down
16 changes: 16 additions & 0 deletions test/finder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,20 @@ describe('finder', () => {
expect(map).toHaveProperty('name', 'map');
expect(map).toHaveProperty(['args', 0, 'value'], '"_id"');
});

it('finds an assignment', async () => {
const source = await loadFixture('kebab-case.prisma');
const finder = createPrismaSchemaBuilder(source);

const generator = finder.findByType('generator', {
name: 'prisma-model-generator',
});
expect(generator).toHaveProperty('name', 'prisma-model-generator');

const assignment = finder.findByType('assignment', {
name: 'fileNamingStyle',
within: generator?.assignments,
});
expect(assignment).toHaveProperty('value', '"kebab"');
});
});

0 comments on commit b69da60

Please sign in to comment.