goagen_js

package module
v0.0.0-...-bae6b37 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2017 License: MIT Imports: 13 Imported by: 0

README

goagen js
==========

This package provides a `goa <https://goa.design/>`_ generator for a modern javascript client module.
This module enabels calling the API actions and varidate these parameters using goa design definition.

Generated JS code are using

- ES 2015
- fetch API (using `whatwg-fetch` library)
- Promise API

You need to *compile* using babel, webpack, or other tool. This compilation is a standard way on the modern JavaScript era.


Presentation Slide: https://speakerdeck.com/shirou/generate-better-javascript-from-goa-design


Status
------------------

Very alpha. you can not use in the production.

- handling JS and goa kind difference.
- array is not work
- required is not work
- re-thinking about `validate()` calling interface. Is this easy to use or not?
- support Flowtype and TypeScript


How to generate JS from your design
---------------------------------------------


At first, you have to do `go get`

::

  % go get github.com/shirou/goagen_js

Then, you can `goagen gen` with your design.

::

  % goagen gen --pkg-path=github.com/shirou/goagen_js -d github.com/some/your/great/design


These two files are generated under `js` directory.

- js/api_request.js
- js/api_validator.js


How to use API
------------------------------------

Invoking API
````````````````````

In the `api_request.js`, each API function is generated and you can use just normal invokation with Promise.

::

  import * as api from "./api_request.js";

  // This API is invoked with query parameter.
  // Query parameter should be passed as object.
  api.FooBar(payload).then((response) => {
    if (response.status !== 200){
      console.log("error", response.status);
    }
    return response.json();
  });


  // This API is invoked with Path Param and POST payload
  // To use this API, passing PathParam and JSON payload as object.
  // This API request to /v2/:fooID/:barType
  api.FooParam(fooID, barType, payload).then((response) => {
    if (response.status !== 200){
      console.log("error", response.status);
    }
    return response.json();
  });


Validation
````````````````

In the `api_validation.js`, there are many `rules` for each APIs and a `validate` function.

::

  import * as v from "./api_validator.js";

  // validate payload
  console.log(v.validate(v.FooBarGet.payload, {
    id: 1,
    too_large_int: 99999,
  }));

  // validate Path Params
  console.log(v.validate(v.FooParamPost.fooID, 99999));

This validate function is used in `api_request.js`. Also you can use to validate before request, for example Form Validation.


Type Anotaion
````````````````````

If `flow` or `type` is specified with `--target` option, type anotation and definition files are generated.

::

  goagen gen --pkg-path=github.com/shirou/goagen_js -d github.com/shirou/goagen_js/example/design -- --target flow

  or

  goagen gen --pkg-path=github.com/shirou/goagen_js -d github.com/shirou/goagen_js/example/design -- --target type --genout ts
  # genout is used to specify output directory name


Then, all of your methods are type anotated like this.

::

  export function UserCreate(userID: number, payload: UserCreatePayload): Promise<UserCreateMedia> {

     ...
  }

Payload are defined on `api.d.ts` file. This is typescript example

::

  declare namespace UserCreatePayload {
    age: number;
    email: string;
    sex: ["male","female","other"];
    name: string;
  }


LICENSE
---------------------

MIT License

Documentation

Overview

Package goagen_js provides a goa generator for a javascript client module. The module exposes functions for calling the API actions. It relies on the fetch API (or using fetch polyfill like https://github.com/github/fetch) to perform the actual HTTP requests.

Output js is es2015 format. So you may need to build using babel https://babeljs.io/.

The generator also produces an validator of API parameters. Since this validator is separeted on each fields, you can use as is, for example form validator.

The controller simply serves all the files under the "js" directory.

Index

Constants

View Source
const (
	TargetJS   = "js"
	TargetFlow = "flow"
	TargetTS   = "typescript"
)

Variables

This section is empty.

Functions

func Generate

func Generate() (files []string, err error)

Generate is the generator entry point called by the meta generator.

Types

type Constraint

type Constraint struct {
	Kind      string        `json:"kind,omitempty"`
	Enum      []interface{} `json:"enum,omitempty"`
	Format    string        `json:"format,omitempty"`
	Pattern   string        `json:"pattern,omitempty"`
	Minimum   *float64      `json:"minimum,omitempty"`
	Maximum   *float64      `json:"maximum,omitempty"`
	MinLength *int          `json:"min_length,omitempty"`
	MaxLength *int          `json:"max_length,omitempty"`
	Required  *bool         `json:"required,omitempty"`
}

type Generator

type Generator struct {
	API    *design.APIDefinition // The API definition
	OutDir string                // Destination directory
	Scheme string                // Scheme used by JavaScript client
	Host   string                // Host addressed by JavaScript client
	Target string                // Target JS (es2015, flowtype, tc)
	// contains filtered or unexported fields
}

Generator is the application code generator.

func NewGenerator

func NewGenerator(options ...Option) *Generator

NewGenerator returns an initialized instance of a JavaScript Client Generator

func (*Generator) Cleanup

func (g *Generator) Cleanup()

Cleanup removes all the files generated by this generator during the last invokation of Generate.

func (*Generator) Generate

func (g *Generator) Generate() ([]string, error)

Generate produces the skeleton main.

type Option

type Option func(*Generator)

Option a generator option definition

func API

func API(API *design.APIDefinition) Option

API The API definition

func Host

func Host(host string) Option

Host addressed by JavaScript client

func OutDir

func OutDir(outDir string) Option

OutDir Path to output directory

func Scheme

func Scheme(scheme string) Option

Scheme Scheme used by JavaScript client

type Param

type Param struct {
	Name          string // no CamelCase name
	CamelCaseName string // CamelCase name
	Kind          string // kind such as bool, number, ...
	Description   string
	Enum          string // Enum name
	// contains filtered or unexported fields
}

type Params

type Params []Param

type ParamsDefinition

type ParamsDefinition struct {
	Action    *design.ActionDefinition
	Base      string
	Name      string
	Path      Params // sorted by goa order
	Query     Params // sorted by alphabetical
	Validator Validator
	Response  *Response
}

func (ParamsDefinition) Comments

func (p ParamsDefinition) Comments(action *design.ActionDefinition) []string

func (ParamsDefinition) FuncArgs

func (p ParamsDefinition) FuncArgs(target string) string

func (ParamsDefinition) FuncName

func (p ParamsDefinition) FuncName() string

func (ParamsDefinition) FuncRet

func (p ParamsDefinition) FuncRet(target string) string

func (ParamsDefinition) PayloadDefinition

func (p ParamsDefinition) PayloadDefinition(target string) []string

func (ParamsDefinition) Request

func (p ParamsDefinition) Request() string

func (ParamsDefinition) ResponseDefinition

func (p ParamsDefinition) ResponseDefinition(target string) []string

func (ParamsDefinition) UrlArgs

func (p ParamsDefinition) UrlArgs() string

func (ParamsDefinition) ValidateRequired

func (p ParamsDefinition) ValidateRequired() bool

type Response

type Response struct {
	Name           string
	Identifier     string
	IdentifierName string
	Params         Params
}

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

func (Validator) JSONify

func (v Validator) JSONify() (string, error)

Directories

Path Synopsis
app
testcase

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL