UNPKG

flow-immutable-models

Version:

Generates model classes from Flow types using Immutable.js

49 lines (37 loc) 2.43 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = initialize; var _getNonClassTypes = require('./getNonClassTypes'); var _getNonClassTypes2 = _interopRequireDefault(_getNonClassTypes); var _flowTypes = require('./flowTypes'); var _typeToExpression = require('./typeToExpression'); var _typeToExpression2 = _interopRequireDefault(_typeToExpression); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function initializeReferencesStatements(j, referenceProps, root) { var nonClassTypes = (0, _getNonClassTypes2.default)(j, root); return referenceProps.filter(function (prop) { return nonClassTypes.indexOf(prop.value.id.name) === -1; }).map(function (prop) { var valueExpression = void 0; var typeAlias = prop.value; var typeExpression = (0, _typeToExpression2.default)(j, typeAlias.id); if ((0, _flowTypes.isImmutableType)(typeAlias)) { valueExpression = j.callExpression(typeExpression, []); } else if (typeAlias.id.name === 'Array') { valueExpression = typeExpression; } else { valueExpression = j.newExpression(typeExpression, []); } return j.expressionStatement(j.assignmentExpression('=', j.identifier('state'), j.callExpression(j.memberExpression(j.identifier('state'), j.identifier('set')), [j.literal(prop.key.name), valueExpression]))); }); } function initialize(j, referenceProps, initialValues, root) { var mapTypeAnnotation = j.typeAnnotation(j.genericTypeAnnotation(j.identifier('Immutable.Map'), j.typeParameterInstantiation([j.stringTypeAnnotation(), j.anyTypeAnnotation()]))); var blockStatements = [j.variableDeclaration('let', [j.variableDeclarator(j.identifier('state'), j.callExpression(j.memberExpression(j.identifier('Immutable'), j.identifier('Map')), initialValues ? [j.identifier(initialValues)] : []))])].concat(_toConsumableArray(initializeReferencesStatements(j, referenceProps, root)), [j.returnStatement(j.identifier('state'))]); var func = j.functionExpression(null, [], j.blockStatement(blockStatements)); func.returnType = mapTypeAnnotation; return j.methodDefinition('method', j.identifier('initialize'), func, false); }