[Serverless] Refactoring: Using Ports and Adapters pattern to refactor code
code to and Using pattern Serverless
2023-09-14 08:59:12 时间
The original code:
createGroup.ts:
import { v4 as uuidv4 } from "uuid"; import "source-map-support/register"; import * as AWS from "aws-sdk"; import { APIGatewayProxyEvent, APIGatewayProxyHandler, APIGatewayProxyResult, } from "aws-lambda"; import { getUserId } from "../../auth/utils"; const docClient = new AWS.DynamoDB.DocumentClient(); const groupTables = process.env.GROUPS_TABLE; export const handler: APIGatewayProxyHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { console.log("Processing event: ", event); const itemId = uuidv4(); const parsedBody = JSON.parse(event.body); const authorization = event.headers.Authorization; const splits = authorization.split(" "); const jwtToken = splits[1]; const newItem = { id: itemId, userId: getUserId(jwtToken), ...parsedBody, }; await docClient .put({ TableName: groupTables, Item: newItem, }) .promise(); return { statusCode: 201, headers: { "Access-Control-Allow-Origin": "*", }, body: JSON.stringify({ newItem, }), }; };
getGroups.ts:
import * as AWS from "aws-sdk"; import { APIGatewayProxyEvent, APIGatewayProxyHandler, APIGatewayProxyResult, } from "aws-lambda"; const docClient = new AWS.DynamoDB.DocumentClient(); const groupTables = process.env.GROUPS_TABLE; export const handler: APIGatewayProxyHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { console.log("Processing event: ", event); const result = await docClient .scan({ TableName: groupTables, }) .promise(); const items = result.Items; return { statusCode: 200, headers: { "Access-Control-Allow-Origin": "*", }, body: JSON.stringify({ items, }), }; };
Tow entry functions both contains busniess logic code and data access code (dynamoDB).
What we want is:
Entry function --> Busniess logic code --> Data access layer
First, create interfaces for both Reqest & Model:
requests/CreateGroupRequest.ts:
export interface CreateGroupRequest { name: string; description: string; }
models/Group.ts:
export interface Group { id: string; name: string; description: string; userId: string; }
Then create data access layer code, it mainly handle all the dynamoDB operations.
dataAccess/groupAccess.ts:
import * as AWS from "aws-sdk"; import { DocumentClient } from "aws-sdk/clients/dynamodb"; import {Group} from '../models/Group' export class GroupAccess { constructor( private readonly docClient: DocumentClient = new AWS.DynamoDB.DocumentClient(), private readonly groupsTable = process.env.GROUPS_TABLE ) { } async getAllGroups(): Promise<Group[]> { console.log('Getting all groups'); const result = await this.docClient.scan({ TableName: this.groupsTable, }).promise() const items = result.Items; return items as Group[]; } async createGroup(group: Group): Promise<Group> { console.log('Creating a group with id', group.id) await this.docClient.put({ TableName: this.groupsTable, Item: group }).promise(); return group; } }
Then create busniessLogic layer, it mainly talk to data access layer and passing and returning the data.
busniessLogic/groups.ts:
import * as uuid from "uuid"; import { Group } from "../models/Group"; import { GroupAccess } from "../dataAccess/groupAccess"; import { CreateGroupRequest } from "../requests/CreateGroupRequest"; import { getUserId } from "../auth/utils"; const groupAccess = new GroupAccess(); export async function getAllGroups(): Promise<Group[]> { return groupAccess.getAllGroups(); } export async function createGroup( createGroupRequest: CreateGroupRequest, jwtToken: string ) { const itemId = uuid.v4(); const userId = getUserId(jwtToken); return await groupAccess.createGroup({ id: itemId, userId: userId, name: createGroupRequest.name, description: createGroupRequest.description, }); }
Lastly, entry function will just talk to busniess layer code:
createGroup.ts:
import "source-map-support/register"; import { APIGatewayProxyEvent, APIGatewayProxyHandler, APIGatewayProxyResult, } from "aws-lambda"; import { createGroup } from "../../busniessLogic/groups"; import { CreateGroupRequest } from "../../requests/CreateGroupRequest"; export const handler: APIGatewayProxyHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { console.log("Processing event: ", event); const newGroup: CreateGroupRequest = JSON.parse(event.body); const authorization = event.headers.Authorization; const splits = authorization.split(" "); const jwtToken = splits[1]; const newItem = await createGroup(newGroup, jwtToken); return { statusCode: 201, headers: { "Access-Control-Allow-Origin": "*", }, body: JSON.stringify({ newItem, }), }; };
getGroups.ts:
import { APIGatewayProxyEvent, APIGatewayProxyHandler, APIGatewayProxyResult, } from "aws-lambda"; import { getAllGroups } from "src/busniessLogic/groups"; export const handler: APIGatewayProxyHandler = async ( event: APIGatewayProxyEvent ): Promise<APIGatewayProxyResult> => { console.log("Processing event: ", event); const items = await getAllGroups(); return { statusCode: 200, headers: { "Access-Control-Allow-Origin": "*", }, body: JSON.stringify({ items, }), }; };
相关文章
- Visual Studio Code 更改侧边栏字体样式(CSS)
- 把 VS Code 添加到右键菜单打开文件和文件夹 ( 其他程序一样 )
- npm install 报错 error code ERR_SOCKET_TIMEOUT解决办法
- 【RocketMQ源码学习错误已解决】之broker启动一直报错。错误code-3。
- Visual Studio Code Jupyter Notebook RCE
- 解决:windows下php curl https时 SSL operation failed with code 1. OpenSSL Error messages: error:1416F086:
- 【错误记录】Ubuntu 中 ROOT 用户无法启动 Visual Studio Code 开发环境 ( 推荐在普通用户下使用 VSCode 开发环境 )
- 【Linux 内核 内存管理】虚拟地址空间布局架构 ④ ( 内存描述符 mm_struct 结构体成员分析 | hiwater_rss | start_code | start_brk )
- Visual Studio Code 1.76 发布
- ORA-48223: Interrupt Requested – Fetch Aborted – Return Code [string] [string] ORACLE 报错 故障修复 远程处理
- SQLServer 错误 15404 无法获取有关 Windows NT 组/用户“user”的信息,错误代码 code。 故障 处理 修复 支持远程
- ORA-13181: unable to determine length of column string_SDOINDEX.SDO_CODE ORACLE 报错 故障修复 远程处理
- ORA-16444: ALTER SYSTEM FLUSH REDO TO STANDBY failed due to a corrupted control file or online log file. ORACLE 报错 故障修复 远程处理
- Oracle 参数 PLSQL_CODE_TYPE 官方解释,作用,如何配置最优化建议
- Illegal unquoted character ((CTRL-CHAR, code X)): has to be escaped using backslash to be included in string value详解编程语言
- Get Your Hands on Linux: Easy Guide to Downloading Source Code Packages(linux源码包下载)
- 利用Oracle TO函数实现数据转换(oracle to_函数)