Google Apps ScriptのWebアプリケーションを公開する機能を利用して、スプレッドシートをデータベースとして扱う簡易的なアプリ・ツールを作りたいケースがあった。
S3やその他のホスティングサイトに構築するほどではないものの、スプレッドシートを直接いじるのは…みたいな時にこの方法でSvelte, React, Vueを利用したWebアプリを作ることが可能だ。
リポジトリ
svelte-with-tailwindcss-on-gas
GitHubのテンプレート機能を利用できるようにしている。
TailwindCSSは不要であれば剥がしてしまって問題ない。
技術スタック
ディレクトリ構成
clientディレクトリ配下がSvelteによって作成されたフロントエンドの実装を集約する層。
serverディレクトリ配下はGAS側で実行されるサーバーサイドの実装を集約する層となっている。
src/├── client/│ ├── api/│ │ ├── mocks│ │ └── index.ts│ ├── components│ ├── features│ ├── stores│ ├── types│ ├── utils│ ├── App.svelte│ └── main.ts├── server/│ ├── main.ts│ └── types.ts└── vite-env.d.tsサーバーサイド
HTMLを配信するためにGASのWebアプリ機能を利用する
server/main.tsにdoGet関数を追加する。
フロントエンド(クライアントサイド)でtitleタグ、faviconの指定を変更しても反映されないため、必要であればdoGet関数内で指定する。
const HTML_TITLE = "App name";const HTML_FAVICON_URL = "https://example.com/favicon.ico";
function doGet() { const html = HtmlService.createTemplateFromFile("index.html").evaluate(); html.setTitle(HTML_TITLE); html.setFaviconUrl(HTML_FAVICON_URL); return html;}APIエンドポイントを作成する
server/main.tsでエンドポイントにしたい関数をexportするだけ。
type APIResult<T> = | { ok: true; data: T; } | { ok: false; error: Error; };
const doSomething = (): APIResult<string> => { return { ok: true, data: "success", };};
export { doSomething };フロントエンド
src/client/api/index.tsでサーバーサイドのAPIと結合させる。
内部的にはgoogle.script.runが実行されている。
import { GASClient } from "gas-client";import type * as Server from "../../server/main";
const { serverFunctions } = new GASClient<typeof Server>();
export const APIClient = serverFunctions;サーバーサイドのAPIを叩く
<script lang="ts"> import { APIClient } from "./api";
const promise = APIClient.doSomething();</script>
{#await promise}<div>Loading...</div>{:then result}<p>{result}</p>{:catch error}<p>error</p>{/await}まとめ
Google Apps ScriptとSvelteを組み合わせることで、スプレッドシートをバックエンドとした高機能なWebアプリを構築できる。
gas-clientライブラリを使えば、型安全にGAS関数を呼び出せるため、開発体験も良好だ。
hsb.horse