LoginSignup
5
1

More than 1 year has passed since last update.

TypeScript で google cloud functions を使う

Last updated at Posted at 2022-12-22

手順

下の記事にまとまっていた。。やや古いようなので若干追記。

  1. npm の環境を作る

    mkdir typescript-function
    cd typescript-function
    npm init -y
    
  2. typescript とcloud functionsのフレームワークをnpmでインストールする。

    npm install @google-cloud/functions-framework
    npm install --save-dev typescript
    
  3. tsconfig.json をつくる。src以下のコードをコンパイルしてdist以下に書き込むように指定している。

    {
      "compilerOptions": {
        "target": "es2016",
        "module": "commonjs",
        "esModuleInterop": true,
        "strict": true,
        "outDir": "dist"
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules"]
    }
    
  4. package.json に追記

    {
      "main": "dist/index.js",
      "scripts": {
        "build": "tsc",
        "start": "functions-framework --target=TypescriptFunction",
        "prestart": "npm run build",
        "gcp-build": "npm run build"
      },
      ...
    }
    
    • main は、コンパイル済みのJavaScript ソースコードを指すようにする。
    • "gcp-build" は、デプロイ時に自動的に呼ばれる。
  5. .gitignore を次のように書いて、npmがインストールしたパッケージやビルド済みのコードがgitにアップロードされないようにする。

    node_modules/
    dist/
    
  6. src/index.ts にコードを書く

    import * as ff from '@google-cloud/functions-framework';
    
    ff.http('TypescriptFunction', (req: ff.Request, res: ff.Response) => {
      res.send('OK');
    });
    
  7. デプロイする。この際、deploy の後ろに書いた文字列が関数名になる。同じ関数名だと古いのを書き潰すので注意。

    gcloud functions deploy TypescriptFunction \
    --gen2
    --runtime nodejs16 \
    --trigger-http \
    --allow-unauthenticated
    
  8. コンソールでデプロイされていることを確認。HTTPトリガの場合は、コンソールでURLを確認。このURLにアクセスすると動作が確認できる。

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1