Skip to content

Commit

Permalink
fix: singleton import
Browse files Browse the repository at this point in the history
  • Loading branch information
pviti committed Dec 7, 2023
1 parent 9e569c7 commit 9578382
Show file tree
Hide file tree
Showing 8 changed files with 284 additions and 111 deletions.
16 changes: 14 additions & 2 deletions gen/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ const templates: { [key: string]: string } = {}

const global: {
version?: string
} = {}
singletons: Record<string, string>
} = { singletons: {} }



Expand Down Expand Up @@ -103,6 +104,13 @@ const generate = async (localSchema?: boolean) => {
if (existsSync(testDir)) rmSync(testDir, { recursive: true })
mkdirSync(testDir, { recursive: true })


// Check singletons
Object.entries(schema.resources).forEach(([type, res]) => {
if (Object.values(res.operations).some(op => op.singleton)) {
global.singletons[type] = Object.keys(res.components)[0]
}
})

const resources: { [key: string]: ApiRes } = {}

Expand Down Expand Up @@ -624,7 +632,10 @@ const generateResource = (type: string, name: string, resource: Resource): strin
// Resources import
const impResMod: string[] = Array.from(declaredImportsModels)
.filter(i => !typesArray.includes(i)) // exludes resource self reference
.map(i => `import type { ${i}${relationshipTypes.has(i)? `, ${i}Type` : ''} } from './${snakeCase(Inflector.pluralize(i))}'`)
.map(i => {
const resFileName = snakeCase(Object.values(global.singletons).includes(i)? i : Inflector.pluralize(i))
return `import type { ${i}${relationshipTypes.has(i)? `, ${i}Type` : ''} } from './${resFileName}'`
})
const importStr = impResMod.join('\n') + (impResMod.length ? '\n' : '')
res = res.replace(/##__IMPORT_RESOURCE_MODELS__##/g, importStr)

Expand Down Expand Up @@ -753,6 +764,7 @@ const templatedComponent = (res: string, name: string, cmp: Component): { compon
let resName = r.type

if (resName !== 'object') {

const relStr = cudModel ? 'Rel' : ''
if (r.polymorphic && r.oneOf) {
resName = r.oneOf.map(o => `${o}${relStr}`).join(' | ')
Expand Down
117 changes: 114 additions & 3 deletions gen/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@
"summary": "Related application membership",
"description": "Related application membership",
"tags": [
"users",
"user",
"has_one"
],
"parameters": [
Expand Down Expand Up @@ -660,6 +660,41 @@
}
}
},
"/memberships/{membershipId}/resend": {
"post": {
"operationId": "POST/memberships/membershipId/resend",
"summary": "Resend invitation",
"description": "Resend invitation for the given membership",
"tags": [
"memberships"
],
"parameters": [
{
"name": "membershipId",
"in": "path",
"schema": {
"type": "string"
},
"required": true,
"description": "The resource's id"
}
],
"requestBody": {
"required": true,
"content": {
"application/vnd.api+json": {
}
}
},
"responses": {
"202": {
"description": "Confirmation that the invitation has been sent",
"content": {
}
}
}
}
},
"/memberships/{membershipId}/organization": {
"get": {
"operationId": "GET/membershipId/organization",
Expand Down Expand Up @@ -894,6 +929,82 @@
}
}
},
"/organizations/{organizationId}/transfer_ownership": {
"patch": {
"operationId": "PATCH/organizations/organizationId/transfer_ownership",
"summary": "Transfer ownership of an organization",
"description": "Transfers the ownership of an organization to a new owner",
"tags": [
"organizations"
],
"parameters": [
{
"name": "organizationId",
"in": "path",
"schema": {
"type": "string"
},
"required": true,
"description": "The resource's id"
}
],
"requestBody": {
"required": true,
"content": {
"application/vnd.api+json": {
"schema": {
"required": [
"data"
],
"type": "object",
"properties": {
"data": {
"type": "object",
"required": [
"type",
"id",
"attributes"
],
"properties": {
"type": {
"type": "string",
"description": "The resource's type",
"enum": [
"organizations"
]
},
"id": {
"type": "string",
"description": "The resource's id",
"example": "XGZwpOSrWL"
},
"attributes": {
"type": "object",
"properties": {
"new_owner_email": {
"type": "string",
"description": "The user email of the new owner of the organization.",
"example": "test@commercelayer.io",
"nullable": false
}
}
}
}
}
}
}
}
}
},
"responses": {
"202": {
"description": "The confirmation of the transfer ownership",
"content": {
}
}
}
}
},
"/organizations/{organizationId}/memberships": {
"get": {
"operationId": "GET/organizationId/memberships",
Expand Down Expand Up @@ -2219,7 +2330,7 @@
"type": "string",
"description": "The resource's type",
"enum": [
"users"
"user"
]
},
"id": {
Expand Down Expand Up @@ -2389,7 +2500,7 @@
"type": "string",
"description": "The resource's type",
"enum": [
"users"
"user"
]
},
"id": {
Expand Down
40 changes: 30 additions & 10 deletions gen/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,33 @@ const operationName = (op: string, id?: string, relationship?: string): string =
}


const referenceResource = (ref: { '$ref': string }): string => {
const referenceResource = (ref: { '$ref': string }): string | undefined => {
const r = getReference(ref) as string
return Inflector.camelize(r.substring(r.lastIndexOf('/') + 1))
return r? Inflector.camelize(r.substring(r.lastIndexOf('/') + 1)) : undefined
}


const referenceContent = (content: any): string => {
return referenceResource(content["application/vnd.api+json"].schema)
const referenceContent = (content: any): string | undefined => {
// No content or no response codes
if (!content || ! Object.keys(content).length) return undefined
const schema = content["application/vnd.api+json"]?.schema
return schema? referenceResource(schema) : undefined
}

/*
const checkSingletonTags = (tags: string[]): boolean => {
console.log(tags)
let singleton = false
if (tags.includes('singleton')) singleton = true
else {
const type = tags.find(t => !t.startsWith('has_'))
singleton = type? (type === Inflector.singularize(type)) : false
}
console.log(singleton)
return singleton
}
*/


const parsePaths = (schemaPaths: any[]): PathMap => {

Expand All @@ -150,7 +167,7 @@ const parsePaths = (schemaPaths: any[]): PathMap => {

const [oKey, oValue] = o

const singleton = oValue.tags.includes('singleton')
const singleton = /* checkSingletonTags(oValue.tags) */ oValue.tags.includes('singleton')

const op: Operation = {
path: pKey,
Expand All @@ -162,9 +179,8 @@ const parsePaths = (schemaPaths: any[]): PathMap => {
if (id) op.id = id
if (oValue.requestBody) op.requestType = referenceContent(oValue.requestBody.content)
if (oValue.responses) {
if (oValue.responses['200']?.content) op.responseType = referenceContent(oValue.responses['200'].content)
else
if (oValue.responses['201']?.content) op.responseType = referenceContent(oValue.responses['201'].content)
const responses = Object.values(oValue.responses) as any[]
if (responses.length > 0) op.responseType = referenceContent(responses[0].content)
}


Expand Down Expand Up @@ -238,6 +254,9 @@ const parseComponents = (schemaComponents: any[]): ComponentMap => {
const cmpRef = getReference(cmp)
if (cmpRef) cmp = resolveReference(schemaComponents, cmpRef)

// Component type
// const cmpType = cmp.properties.type.enum[0]

// Check attributes reference
const attributesRef = getReference(cmp.properties.attributes)
const cmpAttributes = attributesRef ? resolveReference(schemaComponents, attributesRef) : cmp.properties.attributes
Expand Down Expand Up @@ -283,6 +302,7 @@ const parseComponents = (schemaComponents: any[]): ComponentMap => {
}

components[Inflector.camelize(cKey)] = {
// type: cmpType,
attributes,
relationships
}
Expand All @@ -307,13 +327,13 @@ type Resource = {
operations: OperationMap
}


type ResourceMap = {
[resource: string]: Resource
}

type Component = {
attributes: { [key: string]: Attribute },
// type: string
attributes: { [key: string]: Attribute }
relationships: { [key: string]: Relationship }
}

Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"@types/debug": "^4.1.12",
"@types/jest": "^29.5.11",
"@types/lodash": "^4.14.202",
"@types/node": "^20.10.3",
"@types/node": "^20.10.4",
"dotenv": "^16.3.1",
"eslint": "^8.55.0",
"inflector-js": "^1.0.1",
Expand All @@ -56,7 +56,7 @@
"minimize-js": "^1.4.0",
"semantic-release": "^22.0.10",
"ts-node": "^10.9.1",
"typescript": "^5.3.2"
"typescript": "^5.3.3"
},
"repository": "github:commercelayer/provisioning-sdk",
"bugs": "https://github.com/commercelayer/provisioning-sdk/issues",
Expand Down
Loading

0 comments on commit 9578382

Please sign in to comment.