Search code examples
typescriptamazon-web-servicesaws-cdkaws-appsync

Why use CfnAppSync rather than AppSync in CDK project?


We need to add new JS resolvers to our API, and phase out the VTL resolvers, for an AWS AppSync CDK project built with Cfn<> Cloud Front CDK, like this:

          let resolver = new CfnResolver(this, `${r.typeName}_${r.fieldName}`, {
            apiId: graphql.attrApiId,
            typeName: r.typeName,
            fieldName: r.fieldName,
            dataSourceName: r.dataSourceName,
            requestMappingTemplate: readVtl(reqPath, contextVariables),
            responseMappingTemplate: readVtl(resPath, contextVariables),
          });

The latest examples here AWS CDK Example all use the following AppSync CDK directly in this style.

new appsync.Resolver(this, 'pipeline-resolver-create-posts', {
      api,
      typeName: 'Mutation',
      fieldName: 'createPost',
      code: appsync.Code.fromInline(`
          export function request(ctx) {
          return {};
          }

          export function response(ctx) {
          return ctx.prev.result;
          }
  `),
      runtime: appsync.FunctionRuntime.JS_1_0_0,
      pipelineConfig: [add_func_2],
    });

I am struggling to get the CfnResolver to accept new JS resolvers. I have tried as many variations of below as I can and looked here for AWS docs

          let resolver = new CfnResolver(this, `${r.typeName}_${r.fieldName}`, {
            apiId: graphql.attrApiId,
            typeName: r.typeName,
            fieldName: r.fieldName,
            dataSourceName: r.dataSourceName,
            code: readJs(reqPath, contextVariables),
            runtime: CfnResolver.AppSyncRunTime.JS_1_0_0 <-- DOESNT WORK
          });

Can someone suggest either what I'm doing wrong or whether I should give up the Cfn CDK and move to direct AppSync CDK? Many thanks.


Solution

  • The runtime syntax is incorrect in your CfnResolver. Use the FunctionRuntime utility class to set the runtime name (APPSYNC_JS) and version (1.0.0) in one shot:

    runtime: FunctionRuntime.JS_1_0_0,
    

    As @gshpychka says in the comments, though, you are almost always better off using the L2 Resolver construct. The Resolver constructor creates a L1 CfnResolver resource under the hood, but provides better DX. For example, you can put your resolver code in a separate file and reference it with Code.fromAsset('path/to/code.js'), which enables better support for linting, testing and Typescript.