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

feat: orgs service product #19

Merged
merged 7 commits into from
Nov 6, 2023
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as ts from 'typescript'
import path from 'path'
import * as path from 'path'
import { ResolvedProperty, EndpointsInput, EndpointHandlerInfo } from './types'

const typeSyntaxKindToString = (kind: ts.SyntaxKind) => {
Expand Down
4 changes: 4 additions & 0 deletions packages/constructs/reapit-product/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
src
tests
.eslintrc.js
tsconfig.json
51 changes: 51 additions & 0 deletions packages/constructs/reapit-product/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@reapit-cdk/reapit-product",
"version": "0.0.0",
"homepage": "https://github.com/reapit/ts-cdk-constructs/blob/main/packages/constructs/reapit-product",
"description": "Creates a product in the organisations service",
"readme": "https://github.com/reapit/ts-cdk-constructs/blob/main/packages/constructs/reapit-product/readme.md",
"bugs": {
"url": "https://github.com/reapit/ts-cdk-constructs/issues"
},
"license": "MIT",
"scripts": {
"build": "reapit-cdk-tsup --lambda",
"check": "yarn run root:check -p $(pwd)",
"lint": "echo 'skipping...'",
"test": "yarn run root:test -- $(pwd)",
"integ": "yarn run root:integ -- $(pwd)",
"prepack": "yarn build",
"jsii:build": "rpt-cdk-jsii",
"jsii:publish": "rpt-cdk-jsii --publish"
},
"author": {
"name": "Josh Balfour",
"email": "jbalfour@reapit.com"
},
"repository": {
"url": "https://github.com/reapit/ts-cdk-constructs.git"
},
"publishConfig": {
"main": "dist/index.js"
},
"main": "src/index.ts",
"peerDependencies": {
"aws-cdk-lib": "^2.96.2",
"constructs": "^10.2.70"
},
"devDependencies": {
"@reapit-cdk/custom-resource-wrapper": "workspace:^",
"@reapit-cdk/eslint-config": "workspace:^",
"@reapit-cdk/integration-tests": "workspace:^",
"@reapit-cdk/jsii": "workspace:^",
"@reapit-cdk/tsup": "workspace:^",
"aws-cdk-lib": "^2.96.2",
"aws-lambda": "^1.0.7",
"aws-sdk-client-mock": "^3.0.0",
"constructs": "^10.2.70"
},
"dependencies": {
"@reapit/foundations-ts-definitions": "^1.3.55",
"aws-sigv4-fetch": "^2.1.1"
}
}
1 change: 1 addition & 0 deletions packages/constructs/reapit-product/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './reapit-product'
34 changes: 34 additions & 0 deletions packages/constructs/reapit-product/src/lambda/lambda.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { customResourceWrapper } from '@reapit-cdk/custom-resource-wrapper'
import { createProduct, CreateProduct, deleteProduct, updateProduct } from './product'

export const onEvent = customResourceWrapper({
onCreate: async (properties) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { requestId, serviceToken, ...product } = properties
const productObj = await createProduct(product as CreateProduct)
return {
physicalResourceId: productObj.id,
...productObj,
scopes: productObj?.scopes ? productObj.scopes.join(',') : '',
}
},
onUpdate: async (properties) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { requestId, serviceToken, physicalResourceId, ...product } = properties
if (!physicalResourceId) {
throw new Error('no physical resource id present on update request')
}
const productObj = await updateProduct(physicalResourceId, product as CreateProduct)
return {
physicalResourceId: productObj?.id,
...productObj,
scopes: productObj?.scopes ? productObj.scopes.join(',') : '',
}
},
onDelete: async ({ physicalResourceId }) => {
if (!physicalResourceId) {
throw new Error('no physical resource id present on deletion request')
}
await deleteProduct(physicalResourceId)
},
})
90 changes: 90 additions & 0 deletions packages/constructs/reapit-product/src/lambda/product.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { createSignedFetcher } from 'aws-sigv4-fetch'
import { randomUUID } from 'crypto'
import { CreateProductModel, ProductModel } from '@reapit/foundations-ts-definitions/types/organisations-schema'
const headers = {
'content-type': 'application/json',
'api-version': 'latest',
}

const baseUrl = process.env.ORGANISATIONS_SERVICE_URL

if (!baseUrl) {
throw new Error('missing env ORGANISATIONS_SERVICE_URL')
}

const region = process.env.AWS_REGION
if (!region) {
throw new Error('missing env AWS_REGION')
}

const signedFetch = createSignedFetcher({
service: 'execute-api',
region,
})

export type CreateProduct = Omit<CreateProductModel, 'id'>

export const createProduct = async (product: CreateProduct): Promise<ProductModel> => {
const id = randomUUID()
const res = await signedFetch(`${baseUrl}/Products`, {
method: 'post',
body: JSON.stringify({
...product,
id,
}),
headers,
})
if (!res.ok) {
throw new Error('failed to create product')
}
const productId = res.headers.get('location')?.split('/').pop()
if (!productId) {
throw new Error('no product id returned in location header')
}
const productObj = await getProduct(productId)
if (!productObj) {
throw new Error(`Failed to get created product with id ${productId}`)
}
return productObj
}

export const getProduct = async (productId: string): Promise<ProductModel | undefined> => {
const res = await signedFetch(`${baseUrl}/Products/${productId}`, {
method: 'get',
headers,
})
if (res.ok) {
const resp = await res.json()
return resp
}
if (res.status === 404) {
return undefined
}
throw new Error(`Orgs service responded with status code ${res.status}`)
}

export const deleteProduct = async (productId: string) => {
const res = await signedFetch(`${baseUrl}/Products/${productId}`, {
method: 'delete',
headers,
})
if (res.ok) {
return
}
throw new Error(`Orgs service responded with status code ${res.status}`)
}

export const updateProduct = async (id: string, product: CreateProduct) => {
const res = await signedFetch(`${baseUrl}/Products`, {
method: 'post',
body: JSON.stringify({
...product,
id,
}),
headers,
})
if (!res.ok) {
throw new Error('failed to create product')
}
return getProduct(id)
}
53 changes: 53 additions & 0 deletions packages/constructs/reapit-product/src/reapit-product.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Construct } from 'constructs'
import { CreateProductModel, ProductModel } from '@reapit/foundations-ts-definitions/types/organisations-schema'
import { Code, Function, Runtime } from 'aws-cdk-lib/aws-lambda'
import { Provider } from 'aws-cdk-lib/custom-resources'
import { CustomResource, Duration, Token, TokenComparison, Fn } from 'aws-cdk-lib'
import * as path from 'path'

export interface ReapitProductProviderProps {
organisationsServiceUrl: string
}

export type ReapitProduct = Omit<CreateProductModel, 'id'>

export class ReapitProductProvider extends Construct {
provider: Provider

constructor(scope: Construct, id: string, props: ReapitProductProviderProps) {
super(scope, id)

const lambda = new Function(this, 'lambda', {
handler: 'lambda.onEvent',
timeout: Duration.seconds(60),
runtime: Runtime.NODEJS_18_X,
code: Code.fromAsset(path.join(__dirname, '..', 'dist', 'lambda')),
environment: {
ORGANISATIONS_SERVICE_URL: props.organisationsServiceUrl,
},
})
this.provider = new Provider(this, 'provider', {
onEventHandler: lambda,
})
}

createProduct(scope: Construct, id: string, product: ReapitProduct): Required<ProductModel> {
const cr = new CustomResource(scope, id, {
serviceToken: this.provider.serviceToken,
properties: product,
})

const getAttString = (att: keyof ProductModel) => cr.getAttString(att)

return {
id: getAttString('id'),
authFlow: getAttString('authFlow'),
created: getAttString('created'),
externalId: getAttString('externalId'),
scopes: Fn.split(',', getAttString('scopes')),
isInternalApp: Token.compareStrings(getAttString('isInternalApp'), 'true') === TokenComparison.SAME,
name: getAttString('name'),
usageKeyId: getAttString('usageKeyId'),
}
}
}
3 changes: 3 additions & 0 deletions packages/constructs/reapit-product/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "@reapit-cdk/tsconfig/base.json",
}
17 changes: 17 additions & 0 deletions packages/constructs/reapit-product/usage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { CfnOutput, Stack, App } from 'aws-cdk-lib'
import { ReapitProductProvider } from '@reapit-cdk/reapit-product'

const app = new App()
const stack = new Stack(app, 'stack-name')

const productProvider = new ReapitProductProvider(stack, 'product-provider', {
organisationsServiceUrl: '',
})

const product = productProvider.createProduct(stack, 'product', {
name: 'a product name',
})

new CfnOutput(stack, 'client-id', {
value: product.externalId,
})
Loading