示例#1
0
// Generate generates code for the services in the given file.
func (g *jsonschema) Generate(file *generator.FileDescriptor) {
	imp := generator.NewPluginImports(g.gen)
	g.imports = imp
	g.runtimePkg = imp.NewImport("limbo.services/core/runtime/limbo")
	g.operations = nil
	g.definitions = map[string]interface{}{}
	g.dependencies = map[string][]string{}

	for i, enum := range file.Enums() {
		g.generateEnumSchema(file, enum, i)
	}

	for i, message := range file.Messages() {
		g.generateMessageSchema(file, message, i)
	}

	for i, service := range file.Service {
		g.generateServiceSchema(file, service, i)
	}

	if len(g.definitions) > 0 {
		defVarName := fmt.Sprintf("jsonSchemaDefs%x", sha1.Sum([]byte(file.GetName())))
		g.gen.AddInitf(`%s.RegisterSchemaDefinitions(%s)`, g.runtimePkg.Use(), defVarName)
		g.P(`var `+defVarName+` = []`, g.runtimePkg.Use(), `.SchemaDefinition{`)
		var definitionNames = make([]string, 0, len(g.definitions))
		for name := range g.definitions {
			definitionNames = append(definitionNames, name)
		}
		sort.Strings(definitionNames)
		for _, name := range definitionNames {
			def := g.definitions[name]

			data, err := json.MarshalIndent(def, "\t\t", "\t")
			if err != nil {
				panic(err)
			}
			dataStr := strings.Replace(string(data), "`", "`+\"`\"+`", -1)

			g.P(`{`)
			g.P(`Name: `, strconv.Quote(name), `,`)
			g.P(`Dependencies: []string{`)
			for _, dep := range g.dependencies[name] {
				g.P(strconv.Quote(dep), ",")
			}
			g.P(`},`)
			g.P(`Definition: []byte(`, "`", dataStr, "`),")
			g.P(`},`)
		}
		g.P(`}`)
	}

	if len(g.operations) > 0 {
		defVarName := fmt.Sprintf("swaggerDefs%x", sha1.Sum([]byte(file.GetName())))
		g.gen.AddInitf(`%s.RegisterSwaggerOperations(%s)`, g.runtimePkg.Use(), defVarName)
		g.P(`var `+defVarName+` = []`, g.runtimePkg.Use(), `.SwaggerOperation{`)
		for _, op := range g.operations {

			data, err := json.MarshalIndent(op.Swagger, "\t\t", "\t")
			if err != nil {
				panic(err)
			}
			dataStr := strings.Replace(string(data), "`", "`+\"`\"+`", -1)

			g.P(`{`)
			g.P(`Pattern: `, strconv.Quote(op.Pattern), `,`)
			g.P(`Method: `, strconv.Quote(op.Method), `,`)
			g.P(`Dependencies: []string{`)
			for _, dep := range op.Dependencies {
				g.P(strconv.Quote(dep), ",")
			}
			g.P(`},`)
			g.P(`Definition: []byte(`, "`", dataStr, "`),")
			g.P(`},`)
		}
		g.P(`}`)
	}
}