-
Notifications
You must be signed in to change notification settings - Fork 0
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
Add Go code samples #92
Merged
Merged
Changes from all commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
06cb841
Add Go code samples
andrii-balitskyi 6ecd8a3
ci: Generate code
seambot 0c938b9
ci: Format code
seambot 355878f
Fix go request and response string value samples
andrii-balitskyi b458db7
ci: Generate code
seambot dffe5e4
Make go responses to return json, correctly determine go package name
andrii-balitskyi 19c0e49
Imporve readability and structure
andrii-balitskyi 3dfbfba
ci: Generate code
seambot 7f0e7d0
ci: Format code
seambot deec40c
Improve var name
andrii-balitskyi 22f278d
Format
andrii-balitskyi 197cb9f
Add go package import
andrii-balitskyi 91ae178
ci: Generate code
seambot db4cd6f
Improve readability
andrii-balitskyi 6025cb5
ci: Generate code
seambot 0cddf41
Fix sdk imports
andrii-balitskyi 7a2048d
ci: Generate code
seambot 0d3cc1c
Imporve go package name determination and nested imports logic
andrii-balitskyi 08d9c3f
ci: Format code
seambot b638638
Improve var names
andrii-balitskyi 842baff
More renames
andrii-balitskyi 9dc2687
Improve array property value handling
andrii-balitskyi b0fa535
Improve array item check
andrii-balitskyi 829f5ac
Improve object property value handling
andrii-balitskyi 4afc95b
Improve code readability and structure
andrii-balitskyi 3384d75
Improve naming
andrii-balitskyi 9a1ed46
Add comment
andrii-balitskyi 52d95b8
Reorg function order
andrii-balitskyi 00c6f70
Update src/lib/code-sample/go.ts
andrii-balitskyi 382f701
Fix var names casing
andrii-balitskyi 12ccd3a
Merge branch 'main' of github.com:seamapi/blueprint into go-code-samples
andrii-balitskyi 63faa0f
ci: Format code
seambot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
import { pascalCase } from 'change-case' | ||
|
||
import type { Json, NonNullJson } from 'lib/json.js' | ||
|
||
import { createJsonResponse } from './json.js' | ||
import type { CodeSampleDefinition, Context } from './schema.js' | ||
|
||
const defaultGoPackageName = 'api' | ||
const goPackageBasePath = 'github.com/seamapi/go' | ||
|
||
export const createGoRequest = ( | ||
{ request }: CodeSampleDefinition, | ||
_context: Context, | ||
): string => { | ||
const isReqWithParams = Object.keys(request.parameters).length !== 0 | ||
const goPackageName = getGoPackageName(request.path) | ||
|
||
const goSdkImports = generateImports({ | ||
goPackageName, | ||
isReqWithParams, | ||
}) | ||
|
||
const requestStructName = getRequestStructName(request.path) | ||
const formattedArgs = formatGoArgs(request.parameters) | ||
const goSdkRequestArgs = `context.Background()${isReqWithParams ? `, ${goPackageName}.${requestStructName}(${formattedArgs})` : ''}` | ||
|
||
const pathParts = request.path.split('/') | ||
|
||
return `${goSdkImports} | ||
|
||
client${pathParts.map((p) => pascalCase(p)).join('.')}(${goSdkRequestArgs}) | ||
`.trim() | ||
} | ||
|
||
const getGoPackageName = (path: string): string => { | ||
if (!isPathNested(path)) { | ||
return defaultGoPackageName | ||
} | ||
|
||
const firstPathPart = path.split('/').slice(1)[1] | ||
|
||
if (firstPathPart == null) { | ||
throw new Error(`Invalid path: missing second part in "${path}"`) | ||
} | ||
|
||
return firstPathPart.replace(/_/g, '') | ||
} | ||
|
||
const isPathNested = (path: string): boolean => | ||
path.split('/').slice(1).length > 2 | ||
|
||
const generateImports = ({ | ||
goPackageName, | ||
isReqWithParams, | ||
}: { | ||
goPackageName: string | ||
isReqWithParams: boolean | ||
}): string => { | ||
const imports: string[] = [] | ||
|
||
if (isReqWithParams) { | ||
const defaultPackageImport = `import ${defaultGoPackageName} "${goPackageBasePath}"` | ||
imports.push(defaultPackageImport) | ||
} | ||
|
||
if (goPackageName !== defaultGoPackageName && isReqWithParams) { | ||
const nestedPackageImport = `import ${goPackageName} "${goPackageBasePath}/${goPackageName}"` | ||
imports.push(nestedPackageImport) | ||
} | ||
|
||
return imports.join('\n') | ||
} | ||
|
||
const getRequestStructName = (path: string): string => { | ||
const requestStructNameSuffix = 'Request' | ||
|
||
return isPathNested(path) | ||
? `${pascalCase(removeUntilSecondSlash(path))}${requestStructNameSuffix}` | ||
: `${pascalCase(path)}${requestStructNameSuffix}` | ||
} | ||
|
||
const removeUntilSecondSlash = (str: string): string => | ||
str.replace(/^\/[^/]*/, '') | ||
|
||
const formatGoArgs = (jsonParams: NonNullJson): string => | ||
Object.entries(jsonParams as Record<string, Json>) | ||
.map(([paramKey, paramValue]) => { | ||
const formattedValue = formatGoValue({ value: paramValue, key: paramKey }) | ||
return `${pascalCase(paramKey)}: ${formattedValue}` | ||
}) | ||
.join(', ') | ||
|
||
const formatGoValue = ({ | ||
value, | ||
key, | ||
}: { | ||
value: Json | ||
key: string | ||
}): string => { | ||
if (value == null) return 'nil' | ||
if (typeof value === 'string') return `api.String("${value}")` | ||
if (typeof value === 'boolean') return `api.Bool(${value})` | ||
if (typeof value === 'number') return `api.Float64(${value})` | ||
|
||
if (Array.isArray(value)) { | ||
return formatGoArray(value, key) | ||
} | ||
|
||
if (typeof value === 'object') { | ||
return formatGoObject(value, key) | ||
} | ||
|
||
throw new Error(`Unsupported type: ${typeof value}`) | ||
} | ||
|
||
const formatGoArray = (value: Json[], key: string): string => { | ||
if (value.length === 0) { | ||
// in Go there's no way define an empty array without specifying type | ||
// and code samples definitions don't include the type annotations | ||
return 'nil' | ||
} | ||
|
||
const formattedItems = value.map((v) => formatGoValue({ value: v, key })) | ||
const item = value[0] | ||
if (item == null) { | ||
throw new Error(`Null value in response array for '${key}'`) | ||
} | ||
|
||
const arrayType = isPrimitiveValue(item) | ||
? getPrimitiveTypeName(item) | ||
: `api.${pascalCase(key)}` | ||
|
||
return `[${value.length}]${arrayType}{${formattedItems.join(', ')}}` | ||
} | ||
|
||
const isPrimitiveValue = (value: Json): boolean => | ||
value != null && typeof value !== 'object' | ||
|
||
const getPrimitiveTypeName = (value: Json): string => { | ||
switch (typeof value) { | ||
case 'string': | ||
return 'string' | ||
case 'number': | ||
return 'float64' | ||
case 'boolean': | ||
return 'bool' | ||
default: | ||
throw new Error(`Unsupported type: ${typeof value}`) | ||
} | ||
} | ||
|
||
const formatGoObject = (value: Record<string, Json>, key: string): string => { | ||
if (Object.keys(value).length === 0) { | ||
return 'struct{}{}' | ||
} | ||
|
||
const formattedEntries = Object.entries(value) | ||
.map( | ||
([objKey, val]) => | ||
`${pascalCase(objKey)}: ${formatGoValue({ value: val, key: objKey })}`, | ||
) | ||
.join(', ') | ||
|
||
return `api.${pascalCase(key)}{${formattedEntries}}` | ||
} | ||
|
||
export const createGoResponse = createJsonResponse | ||
andrii-balitskyi marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is an example where the import is not
import api "github.com/seamapi/go
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For ex.,
import acs "github.com/seamapi/go/acs
foracs.UsersListAccessibleEntrancesRequest
orimport accesscodes "github.com/seamapi/go/accesscodes
foraccesscodes.UnmanagedConvertToManagedRequest
orimport useridentities "github.com/seamapi/go/useridentities
foruseridentities.EnrollmentAutomationsDeleteRequest
etc.