Skip to content
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

feature/delete schema function #147

Closed
Closed
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]

### Added

- Delete schemas function

### Added

- Schema client created

## [1.5.3] - 2023-05-04

### Fixed
Expand Down
1 change: 1 addition & 0 deletions graphql/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type Query {
filter: AffiliatesFilterInput
sorting: AffliatesSortingInput
): [AffiliateScroll]!
getWorkspaces: [Workspaces]
}

type Mutation {
Expand Down
4 changes: 4 additions & 0 deletions graphql/types/workspaces.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
type Workspaces {
name: String
production: Boolean
}
7 changes: 4 additions & 3 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@
},
{
"name": "colossus-write-logs"
},
{
"name": "read-write-any-workspace"
}
],
"settingsSchema": {
Expand All @@ -100,9 +103,7 @@
},
"billingOptions": {
"type": "free",
"availableCountries": [
"*"
],
"availableCountries": ["*"],
"support": {
"url": "https://support.vtex.com/hc/requests"
}
Expand Down
5 changes: 5 additions & 0 deletions node/clients/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Affiliates, UserAffiliation } from 'vtex.affiliates'

import AuthenticationClient from './authenticationClient'
import CheckoutExtended from './checkout'
import SchemasClient from './schemas'

export class Clients extends IOClients {
public get affiliates() {
Expand All @@ -24,4 +25,8 @@ export class Clients extends IOClients {
public get authentication() {
return this.getOrSet('authentication', AuthenticationClient)
}

public get schemas() {
return this.getOrSet('schemas', SchemasClient)
}
}
36 changes: 36 additions & 0 deletions node/clients/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { InstanceOptions, IOContext, RequestConfig } from '@vtex/api'
import { ExternalClient } from '@vtex/api'

const routes = {
schemas: (dataEntity: string) => `/dataentities/${dataEntity}/schemas`,
delete: (dataEntity: string, schemaName: string) =>
`dataentities/${dataEntity}/schemas/${schemaName}`,
}

export default class SchemasClient extends ExternalClient {
constructor(context: IOContext, options?: InstanceOptions) {
super(`http://${context.account}.myvtex.com/api`, context, {
...options,
headers: {
...options?.headers,
VtexIdclientAutCookie: context.authToken,
'Content-Type': 'application/json',
},
})
}

public getSchemas(
dataEntity: string,
config?: RequestConfig
): Promise<unknown[]> {
return this.http.get(routes.schemas(dataEntity), config)
}

public deleteSchemas(
dataEntity: string,
schemaName: string,
config?: RequestConfig
): Promise<unknown> {
return this.http.delete(routes.delete(dataEntity, schemaName), config)
}
}
12 changes: 10 additions & 2 deletions node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ import { updateAffiliate as updateAffiliateResolver } from './resolvers/updateAf
import { getAffiliate } from './resolvers/getAffiliate'
import { fieldResolvers } from './resolvers/fieldResolvers'
import { getAffiliateByEmail } from './resolvers/getAffiliateByEmail'
import { getWorkspaces } from './resolvers/getWorkspaces'
import { getSchemas } from './middlewares/getSchemas'
import { deleteSchemas } from './middlewares/deleteSchemas'

const TIMEOUT_MS = 1000

Expand Down Expand Up @@ -75,10 +78,10 @@ declare global {
// The shape of our State object found in `ctx.state`. This is used as state bag to communicate between middlewares.
interface State extends RecorderState {
affiliate?: AffiliateInput
schemas?: string[]
}

interface UserLoginState extends RecorderState {
affiliate?: AffiliateInput
interface UserLoginState extends State {
orderForm: OrderForm
userProfileId?: string | null
affiliateLead: AffiliateLead
Expand All @@ -89,6 +92,10 @@ declare global {
export default new Service({
clients,
routes: {
schemas: method({
GET: [getSchemas],
DELETE: [getSchemas, deleteSchemas],
}),
affiliate: method({
POST: [authenticateRequest, validateCreate, createAffiliate],
PATCH: [authenticateRequest, validateUpdate, updateAffiliate],
Expand All @@ -112,6 +119,7 @@ export default new Service({
getAffiliate,
getAffiliateByEmail,
getAffiliatesScroll,
getWorkspaces,
},
Mutation: {
addAffiliate,
Expand Down
30 changes: 30 additions & 0 deletions node/middlewares/deleteSchemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export async function deleteSchemas(
ctx: Context,
next: () => Promise<unknown>
) {
const {
clients: { schemas },
state,
vtex: { logger },
} = ctx

try {
const schemasToDelete = state?.schemas ?? []

schemasToDelete.forEach(async (i) => {
await schemas.deleteSchemas('vtex_affiliates_Affiliates', i)
})
} catch (err) {
logger.error({
metric: 'delete-affiliate-schema',
message: err.message,
})
throw new Error('Error deleting affiliate schemas')
}

ctx.message = `Schema Deleted`
ctx.body = `Schema Deleted`
ctx.status = 200

await next()
}
45 changes: 45 additions & 0 deletions node/middlewares/getSchemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { getOldVersions } from '../utils/schemas'

export async function getSchemas(ctx: Context, next: () => Promise<unknown>) {
const {
clients: { schemas, apps },
state,
vtex: { logger },
} = ctx

const manifest = await apps.getApp(`vtex.affiliates`)
const versionManifest = manifest?.version.split(`+`)

try {
let allSchemas: string[] = []

const schemaList = await schemas.getSchemas('vtex_affiliates_Affiliates')

schemaList.forEach((s: any) => {
allSchemas = [...allSchemas, s.name]
})

const allOldSchemas = allSchemas.filter(
(schema) => !schema.includes(versionManifest[0])
)

const oldVersions = getOldVersions(allOldSchemas, versionManifest[0])

const filteredSchemas = allSchemas.filter(
(schema) =>
!schema.includes(versionManifest[0]) &&
!schema.includes(oldVersions[0]) &&
!schema.includes(oldVersions[1])
)

state.schemas = filteredSchemas
} catch (err) {
logger.error({
metric: 'get-affiliate-schema',
message: err.message,
})
throw new Error('Error getting affiliate schemas')
}

await next()
}
2 changes: 1 addition & 1 deletion node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"@types/jest": "^27.0.2",
"@types/node": "^12.0.0",
"@types/ramda": "types/npm-ramda#dist",
"@vtex/api": "6.45.12",
"@vtex/api": "6.45.22",
"@vtex/test-tools": "^3.4.1",
"@vtex/tsconfig": "^0.5.6",
"typescript": "3.9.7"
Expand Down
6 changes: 6 additions & 0 deletions node/resolvers/getWorkspaces.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const getWorkspaces = async (_: unknown, __: unknown, ctx: Context) => {
const { workspaces } = ctx.clients
const result = await workspaces.list(ctx.vtex.account)

return result
}
4 changes: 4 additions & 0 deletions node/service.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
"maxReplicas": 4,
"workers": 1,
"routes": {
"schemas": {
"path": "/_v/affiliateSchemas",
"public": true
},
"affiliate": {
"path": "/_v/affiliate",
"public": true
Expand Down
46 changes: 46 additions & 0 deletions node/utils/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
function isVersionLower(currentVersion: string, newVersion: string) {
const current = currentVersion.split('.').map(Number)
const newV = newVersion.split('.').map(Number)

for (let i = 0; i < Math.max(current.length, newV.length); i++) {
if (current[i] > (newV[i] || 0)) {
return false
}

if (current[i] < (newV[i] || 0)) {
return true
}
}

return false
}

function compareVersions(version1: string, version2: string) {
const v1 = version1.split('.').map(Number)
const v2 = version2.split('.').map(Number)

for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
if (v1[i] > v2[i]) return -1
if (v1[i] < v2[i]) return 1
}

return 0
}

export function getOldVersions(versions: any[], manifest: string) {
let versionArray: string[] = []

versions.forEach((version) => {
const splitted = version.split('-')

if (
splitted[0].match(/^\d/) &&
!versionArray.includes(splitted) &&
!isVersionLower(manifest, splitted[0])
) {
versionArray = [...versionArray, splitted[0]]
}
})

return versionArray.slice().sort(compareVersions)
}
Loading
Loading