Create utilities for module generators

Summary:
There are two operations we do in every NativeModule generator:
- We convert the `SchemaType` into a map of NativeModule schemas
- If the type-annotation is a TypeAliasTypeAnnotation, we resolve it by doing a lookup on the NativeModuleAliasMap. This is usually followed by an invariant to assert that the lookup didn't fail.

Both procedures have been translated into utilities for use across our generators. I also deleted `getTypeAliasTypeAnnotation` which will no longer be used.

Changelog: [Internal]

Reviewed By: hramos

Differential Revision: D23667249

fbshipit-source-id: 4e34078980e2caa4daed77c38b1168bfc161c31c
This commit is contained in:
Ramanpreet Nara
2020-09-29 14:39:40 -07:00
committed by Facebook GitHub Bot
parent 5f5ccfcb2c
commit c300193853
+33 -25
View File
@@ -10,35 +10,43 @@
'use strict';
import type {ObjectTypeAliasTypeShape} from '../../CodegenSchema';
import type {
SchemaType,
NativeModuleAliasMap,
Required,
NativeModuleObjectTypeAnnotation,
NativeModuleSchema,
} from '../../CodegenSchema';
function getTypeAliasTypeAnnotation(
name: string,
aliases: $ReadOnly<{[aliasName: string]: ObjectTypeAliasTypeShape, ...}>,
): $ReadOnly<ObjectTypeAliasTypeShape> {
const typeAnnotation = aliases[name];
if (!typeAnnotation) {
throw Error(`No type annotation found for "${name}" in schema`);
}
if (typeAnnotation.type === 'ObjectTypeAnnotation') {
if (typeAnnotation.properties) {
return typeAnnotation;
}
const invariant = require('invariant');
throw new Error(
`Unsupported type for "${name}". Please provide properties.`,
export type AliasResolver = (
aliasName: string,
) => Required<NativeModuleObjectTypeAnnotation>;
function createAliasResolver(aliasMap: NativeModuleAliasMap): AliasResolver {
return (aliasName: string) => {
const alias = aliasMap[aliasName];
invariant(alias != null, `Unable to resolve type alias '${aliasName}'.`);
return alias;
};
}
function getModules(
schema: SchemaType,
): $ReadOnly<{|[moduleName: string]: NativeModuleSchema|}> {
return Object.keys(schema.modules)
.map<?{+[string]: NativeModuleSchema}>(
moduleName => schema.modules[moduleName].nativeModules,
)
.filter(Boolean)
.reduce<{+[string]: NativeModuleSchema}>(
(acc, modules) => ({...acc, ...modules}),
{},
);
}
// $FlowFixMe[incompatible-type]
if (typeAnnotation.type === 'TypeAliasTypeAnnotation') {
return getTypeAliasTypeAnnotation(typeAnnotation.name, aliases);
}
throw Error(
`Unsupported type annotation in alias "${name}", found: ${typeAnnotation.type}`,
);
}
module.exports = {
getTypeAliasTypeAnnotation,
createAliasResolver,
getModules,
};