Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat: Add support for json omitempty and embedded structs in apitypings #1318

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ site/out/index.html: $(shell find ./site -not -path './site/node_modules/*' -typ
# Restores GITKEEP files!
git checkout HEAD site/out

site/src/api/typesGenerated.ts: $(shell find codersdk -type f -name '*.go')
site/src/api/typesGenerated.ts: scripts/apitypings/main.go $(shell find codersdk -type f -name '*.go')
go run scripts/apitypings/main.go > site/src/api/typesGenerated.ts
cd site && yarn run format:types

Expand Down
6 changes: 3 additions & 3 deletions codersdk/pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ type Pagination struct {
// Offset for better performance. To use it as an alternative,
// set AfterID to the last UUID returned by the previous
// request.
AfterID uuid.UUID `json:"after_id"`
AfterID uuid.UUID `json:"after_id,omitempty"`
// Limit sets the maximum number of users to be returned
// in a single page. If the limit is <= 0, there is no limit
// and all users are returned.
Limit int `json:"limit"`
Limit int `json:"limit,omitempty"`
// Offset is used to indicate which page to return. An offset of 0
// returns the first 'limit' number of users.
// To get the next page, use offset=<limit>*<page_number>.
// Offset is 0 indexed, so the first record sits at offset 0.
Offset int `json:"offset"`
Offset int `json:"offset,omitempty"`
}

// asRequestOption returns a function that can be used in (*Client).request.
Expand Down
31 changes: 28 additions & 3 deletions scripts/apitypings/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,31 @@ func (g *Generator) posLine(obj types.Object) string {
func (g *Generator) buildStruct(obj types.Object, st *types.Struct) (string, error) {
var s strings.Builder
_, _ = s.WriteString(g.posLine(obj))
_, _ = s.WriteString(fmt.Sprintf("export interface %s ", obj.Name()))

_, _ = s.WriteString(fmt.Sprintf("export interface %s {\n", obj.Name()))
// Handle named embedded structs in the codersdk package via extension.
var extends []string
extendedFields := make(map[int]bool)
for i := 0; i < st.NumFields(); i++ {
field := st.Field(i)
tag := reflect.StructTag(st.Tag(i))
// Adding a json struct tag causes the json package to consider
// the field unembedded.
if field.Embedded() && tag.Get("json") == "" && field.Pkg().Name() == "codersdk" {
extendedFields[i] = true
extends = append(extends, field.Name())
}
}
if len(extends) > 0 {
_, _ = s.WriteString(fmt.Sprintf("extends %s ", strings.Join(extends, ", ")))
}

_, _ = s.WriteString("{\n")
// For each field in the struct, we print 1 line of the typescript interface
for i := 0; i < st.NumFields(); i++ {
if extendedFields[i] {
continue
}
field := st.Field(i)
tag := reflect.StructTag(st.Tag(i))

Expand All @@ -251,6 +272,10 @@ func (g *Generator) buildStruct(obj types.Object, st *types.Struct) (string, err
if jsonName == "" {
jsonName = field.Name()
}
jsonOptional := false
if len(arr) > 1 && arr[1] == "omitempty" {
jsonOptional = true
}

var tsType TypescriptType
// If a `typescript:"string"` exists, we take this, and do not try to infer.
Expand All @@ -273,7 +298,7 @@ func (g *Generator) buildStruct(obj types.Object, st *types.Struct) (string, err
_, _ = s.WriteRune('\n')
}
optional := ""
if tsType.Optional {
if jsonOptional || tsType.Optional {
optional = "?"
}
_, _ = s.WriteString(fmt.Sprintf("%sreadonly %s%s: %s\n", indent, jsonName, optional, tsType.ValueType))
Expand Down Expand Up @@ -322,7 +347,7 @@ func (g *Generator) typescriptType(ty types.Type) (TypescriptType, error) {
return TypescriptType{
ValueType: "any",
AboveTypeLine: fmt.Sprintf("%s\n%s",
indentedComment("Embedded struct, please fix by naming it"),
indentedComment("Embedded anonymous struct, please fix by naming it"),
indentedComment("eslint-disable-next-line @typescript-eslint/no-explicit-any"),
),
}, nil
Expand Down
24 changes: 11 additions & 13 deletions site/src/api/typesGenerated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export interface CreateWorkspaceBuildRequest {
// This is likely an enum in an external package ("github.com/coder/coder/coderd/database.WorkspaceTransition")
readonly transition: string
readonly dry_run: boolean
readonly state: string
readonly state?: string
}

// From codersdk/organizations.go:52:6
Expand Down Expand Up @@ -149,9 +149,9 @@ export interface OrganizationMember {

// From codersdk/pagination.go:11:6
export interface Pagination {
readonly after_id: string
readonly limit: number
readonly offset: number
readonly after_id?: string
readonly limit?: number
readonly offset?: number
}

// From codersdk/parameters.go:26:6
Expand Down Expand Up @@ -185,7 +185,7 @@ export interface ProvisionerJob {
readonly created_at: string
readonly started_at?: string
readonly completed_at?: string
readonly error: string
readonly error?: string
readonly status: ProvisionerJobStatus
readonly worker_id?: string
}
Expand Down Expand Up @@ -264,9 +264,8 @@ export interface TemplateVersionParameterSchema {
}

// From codersdk/templates.go:74:6
export interface TemplateVersionsByTemplateRequest {
export interface TemplateVersionsByTemplateRequest extends Pagination {
readonly template_id: string
readonly Pagination: Pagination
}

// From codersdk/templates.go:28:6
Expand Down Expand Up @@ -323,10 +322,9 @@ export interface UserRoles {
}

// From codersdk/users.go:23:6
export interface UsersRequest {
export interface UsersRequest extends Pagination {
readonly search: string
readonly status: string
readonly Pagination: Pagination
}

// From codersdk/workspaces.go:18:6
Expand Down Expand Up @@ -355,12 +353,12 @@ export interface WorkspaceAgent {
readonly status: WorkspaceAgentStatus
readonly name: string
readonly resource_id: string
readonly instance_id: string
readonly instance_id?: string
readonly architecture: string
readonly environment_variables: Record<string, string>
readonly operating_system: string
readonly startup_script: string
readonly directory: string
readonly startup_script?: string
readonly directory?: string
}

// From codersdk/workspaceagents.go:47:6
Expand Down Expand Up @@ -415,7 +413,7 @@ export interface WorkspaceResource {
readonly workspace_transition: string
readonly type: string
readonly name: string
readonly agents: WorkspaceAgent[]
readonly agents?: WorkspaceAgent[]
}

// From codersdk/parameters.go:16:6
Expand Down