Example #1
0
export function generateProxy(
  serviceName: string,
  preserveFunctionNames: boolean,
  defs: Definitions,
): string {
  const statements = [];

  // Declare remoteModule as empty object.
  statements.push(
    t.variableDeclaration('const', [
      t.variableDeclarator(t.identifier('remoteModule'), emptyObject),
    ])
  );

  defs.forEach(definition => {
    const name = definition.name;
    switch (definition.kind) {
      case 'function':
        const functionName = preserveFunctionNames ? name : `${serviceName}/${name}`;
        // Generate a remote proxy for each module-level function.
        statements.push(t.assignmentExpression('=',
          t.memberExpression(remoteModule, t.identifier(name)),
          generateFunctionProxy(functionName, definition.type)));
        break;
      case 'interface':
        // Generate a remote proxy for each remotable interface.
        statements.push(t.assignmentExpression('=',
          t.memberExpression(remoteModule, t.identifier(name)),
          generateInterfaceProxy(definition)));
        break;
      case 'alias':
        // nothing
        break;
    }
  });

  // Return the remote module.
  statements.push(t.returnStatement(remoteModule));

  // Node module dependencies are added via the `inject` function, instead of
  // requiring them. This eliminates having to worry about module resolution.
  // In turn, that makes colocating the definition and the constructed proxy
  // easier for internal and external services.
  const deps = dependenciesNodes(['Observable', 'trackOperationTiming']);

  // Wrap the remoteModule construction in a function that takes a RpcConnection
  // object as an argument.
  const func = t.arrowFunctionExpression([clientIdentifier], t.blockStatement(statements));
  const assignment = t.assignmentExpression('=', moduleDotExportsExpression, func);
  const program = t.program([
    // !!!This module is not transpiled!!!
    t.expressionStatement(t.literal('use strict')),
    deps.declaration,
    t.expressionStatement(assignment),
    t.expressionStatement(objectDefinePropertyCall('inject', deps.injectionCall)),
    t.expressionStatement(objectDefinePropertyCall('defs', objectToLiteral(defs))),
  ]);

  // Use Babel to generate code from the AST.
  return generate(program).code;
}
Example #2
0
 names.map((name, i) => t.expressionStatement(
   t.assignmentExpression('=',
     t.identifier(name),
     t.memberExpression(t.identifier('arguments'), t.literal(i)),
   )
 ))