GolangのgoaでAPIをデザインしよう(クライアント編)
goaはいいぞ!
Golangのgoaの勉強に役立つ情報まとめ - ぺい
goaの情報をもっと見たい方は、上のリンクから確認してください
クライアント編
バックエンドをいい感じに出来るgoaですけど、欲を言えばクライアント側もいい感じにしてほしい。実はいい感じにしてくれます。とは言ってもちょっとした手助けをしてくれる感じです。
対応しているのは、JavascriptでのAPIへのリクエストです。
$ go get github.com/tikasan/goa-simple-sample または $ ghq get github.com/tikasan/goa-simple-sample
今回はgoaのサンプルを作成しているリポジトリを使って説明したいと思います。 本来は以下のコマンドで実行して、クライアント側のコードを生成しますが、出来上がっているので、生成されたものを見てみましょう。
goagen js -d github.com/tikasan/goa-simple-sample/design
// This module exports functions that give access to the goa simple sample API hosted at localhost:8080. // It uses the axios javascript library for making the actual HTTP requests. define(['axios'] , function (axios) { function merge(obj1, obj2) { var obj3 = {}; for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; } for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; } return obj3; } return function (scheme, host, timeout) { scheme = scheme || 'http'; host = host || 'localhost:8080'; timeout = timeout || 20000; // Client is the object returned by this module. var client = axios; // URL prefix for all API requests. var urlPrefix = scheme + '://' + host; // 複数アクション(:ID) // path is the request path, the format is "/api/v1/actions/:ID" // config is an optional object to be merged into the config built by the function prior to making the request. // The content of the config object is described here: https://github.com/mzabriskie/axios#request-api // This function returns a promise which raises an error if the HTTP response is a 4xx or 5xx. client.IDActions = function (path, config) { cfg = { timeout: timeout, url: urlPrefix + path, method: 'get', responseType: 'json' }; if (config) { cfg = merge(cfg, config); } return client(cfg); } ---------------------------------------------------------------- // Validation // path is the request path, the format is "/api/v1/validation" // ID, defaultType, email, enumType, integerType, reg, stringType are used to build the request query string. // config is an optional object to be merged into the config built by the function prior to making the request. // The content of the config object is described here: https://github.com/mzabriskie/axios#request-api // This function returns a promise which raises an error if the HTTP response is a 4xx or 5xx. client.validationValidation = function (path, ID, defaultType, email, enumType, integerType, reg, stringType, config) { cfg = { timeout: timeout, url: urlPrefix + path, method: 'get', params: { id: id, defaultType: defaultType, email: email, enumType: enumType, integerType: integerType, reg: reg, stringType: stringType }, responseType: 'json' }; if (config) { cfg = merge(cfg, config); } return client(cfg); } return client; }; });
jsでそのまま使えるリクエスト集が出来上がりました。
この機能を知った時は感動しましたが、あまりに楽すぎてダメ人間になりそうと思ったので、今後も使っていこうと思います。(?)