CI/CD of cloud functions using Typescript and Cloudbuild

Image for post
Image for post
Photo by Luís Perdigão on Unsplash
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution":"node",
"lib": ["es6"],
"allowJs": true,
"outDir": "build",
"rootDir": "src",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Image for post
Image for post
import axios from "axios";
const webHookSubscriber = async(event:any,context:any)=>{
console.log("Received Message");
const message = event.data
? Buffer.from(event.data, 'base64').toString()
: 'Hello, World';
try{
await axios.post(process.env.WEBHOOK_URL,message);
}catch(err){
console.log(err);
}
}export {
webHookSubscriber
}

Note: Google also has a Typescript boilerplate setup readily available here. It’s pretty easy to set up and configure if you need a quick start solution. However in this story I have not used that. It’s because I need to avoid the coupling with that package so that with minimal change I can move across different cloud solutions.

steps:
- name: 'gcr.io/cloud-builders/npm'
args: [ 'install']
- name: 'gcr.io/cloud-builders/npm'
args: [ 'run','build']
- name: 'bash'
args: [cp,'package.json','build']
- name: 'bash'
args: [cp,'package-lock.json','build']
- name: gcr.io/cloud-builders/gcloud
args: [ functions, deploy, YOUR_APP_NAME,--source,build,--trigger-topic,YOUR_PUBSUB_TOPIC,--entry-point,webHookSubscriber,--runtime,nodejs10,--ingress-settings,internal-only,--retry,--max-instance,'2',--set-env-vars,WEBHOOK_URL=yourwebhookurl]
gcloud builds submit --config cloudbuild.yaml
steps:
- name: 'gcr.io/cloud-builders/npm'
args: [ 'install']
- name: 'gcr.io/cloud-builders/npm'
args: [ 'run','build']
- name: 'bash'
args: [cp,'package.json','build']
- name: 'bash'
args: [cp,'package-lock.json','build']
- name: gcr.io/cloud-builders/gcloud
args: [ functions, deploy, YOUR_APP_NAME,--source,build,--trigger-topic,YOUR_PUBSUB_TOPIC,--entry-point,webHookSubscriber]

Note that if you only have tsc command as your build keep in mind that it will not copy any other static files which are not recognised by the typescript compiler. So you may want to handle that in additional build steps.

learning to be a javaScripter and an eGOist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store