Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AWS Lambda Invoke NestJS Sample, main method: private async invoker
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