Another question on the `Api` construct: I'm defin...
# sst
p
Another question on the
Api
construct: I'm defining my full application spread out in multiple services, each with their own
sst-stack.js
file that is replacing my old
serverless.yml
files. I also have some common functions they use. In order to have all my routes use the same custom domain, it seems it would be smart to use a single Api and have each service add their routes to it. I didn't see any support for adding to the construct outside the constructor but wanted to check - is this supported? Does it sound like a reasonable idea? Does this move beyond your plans for SST and would be better handled in native CDK?
f
You should be able to pass the created Http Api from 1 stack to another. So in stackA:
Copy code
const { httpApi } = new sst.Api(...);
this.httpApi = httpApi;
In
index.js
pass httpApi to stackB:
Copy code
const stackA = new StackA(...);

new StackB(app, "StackB", {
  httpApi: stackA.httpApi
});
Then in stackB:
Copy code
new sst.Api(this, "Api", {
  httpApi: props.httpApi,
  routes: { ... }
});
Give this a try and let me know if it works for you.
p
Yeah, it seems to work, but tricky to make it work ok with custom domains. Keep getting
Copy code
[Error at /test-peasy-cognito/CommonApi] Found zones: [] for dns:<http://mydomain.com|mydomain.com>, privateZone:undefined, vpcId:undefined, but wanted exactly 1 zone
I already have other mappings to this same domain, so I'm sure it's something in AWS, just tricky to find the correct magic spell. Was hoping I could create new mapping just by using a different path:
Copy code
this.apiV2p1 = new sst.Api(this, 'CommonApi', {
      customDomain: {
        domainName: scope.stage === 'production' ? '<http://v2.api.mydomain.com|v2.api.mydomain.com>' : `${scope.stage}.<http://api.mydomain.com|api.mydomain.com>`,
        hostedZone: '<http://mydomain.com|mydomain.com>',
        path: 'v2.1'
      },
      routes: {
        'GET  /ping': 'resources/domains/handler.ping'
      }
    })
Also notices I must have routes defined, not possible to just create an Api without routes first
f
@Pål Brattberg the error seems to suggest it’s not able to find a hosted zone in Route 53
Do you have ‘mydomain.com’ in your Route 53?
p
Yeah, but It's only in one account and I have different accounts for my different stages
f
Oh i see. Is this error happening in a different account (not the account that has the domain)?
@Pål Brattberg We added support for lazily adding routes in v0.9.15 Here’s an example https://docs.serverless-stack.com/constructs/Api#lazily-adding-routes So with this, the cleanest way to share an Api across stacks is to create the Api in stackA, pass
stackA.api
to stackB, then call
api.addRoutes
in stackB. Let me know if this makes sense.
p
Makes a lot of sense @Frank, thank you! 👏