Last active
June 19, 2019 03:38
-
-
Save sofyan-ahmad/0657b186cb093d00c6cf36687e3093c9 to your computer and use it in GitHub Desktop.
AWS Lambda Invoke NestJS Sample, main method: private async invoker
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
import { HttpException, Injectable } from '@nestjs/common'; | |
import { Lambda } from 'aws-sdk'; | |
import UserRepresentation from 'keycloak-admin/lib/defs/userRepresentation'; | |
@Injectable() | |
export class AccountService { | |
private realm: string = process.env.KEYCLOAK_REALM; | |
private lambda: Lambda = new Lambda({ | |
region: process.env.AWS_REGION, | |
}); | |
async createAccount(user: UserRepresentation): Promise<{ id: string }> { | |
const headers: any = {}; | |
headers.accept = 'application/json'; | |
headers['Content-Type'] = 'application/json'; | |
const params: Lambda.Types.InvocationRequest = { | |
FunctionName: process.env.KEYCLOAK_SERVICE_NAME, | |
InvocationType: 'RequestResponse', | |
Payload: JSON.stringify({ | |
resource: '/{proxy+}', | |
path: `/accounts/${this.realm}`, | |
headers, | |
body: JSON.stringify(user), | |
httpMethod: 'POST', | |
}), | |
}; | |
return JSON.parse(await this.invoker(params)) as { id: string }; | |
} | |
private async invoker( | |
params: Lambda.Types.InvocationRequest | |
): Promise<string> { | |
const result = await this.lambda.invoke(params).promise(); | |
const resPayload: { | |
statusCode: number; | |
body: string; | |
headers: any; | |
} = JSON.parse(result.Payload.toString()); | |
if (resPayload.statusCode === 500) { | |
console.info(result); | |
throw new HttpException( | |
resPayload.body || 'Cannot create account', | |
resPayload.statusCode | |
); | |
} | |
return resPayload.body; | |
} | |
// async updateAccount( | |
// id: string, | |
// user: UserRepresentation, | |
// realm: string | |
// ): Promise<void> { | |
// const client = await this.getKeycloakClient(); | |
// try { | |
// await client.users.update({ id, realm }, user); | |
// } catch (e) { | |
// this.throwHttpError(e); | |
// } | |
// } | |
// async deleteAccountById( | |
// id: string, | |
// realm: string, | |
// softDelete?: boolean | |
// ): Promise<void> { | |
// const client = await this.getKeycloakClient(); | |
// try { | |
// if (softDelete) { | |
// await client.users.update({ id, realm }, { enabled: false }); | |
// } else { | |
// await client.users.del({ id, realm }); | |
// } | |
// } catch (e) { | |
// this.throwHttpError(e); | |
// } | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment