Skip to content

Instantly share code, notes, and snippets.

@gufranco
Last active May 25, 2021 13:12
Show Gist options
  • Save gufranco/62bf5db6479c8c54c26d252ef1d96539 to your computer and use it in GitHub Desktop.
Save gufranco/62bf5db6479c8c54c26d252ef1d96539 to your computer and use it in GitHub Desktop.
import HttpService from '../services/HttpService'
import { AxiosResponse } from 'axios'
import OrderInterface from '../interfaces/OrderInterface'
import * as AWS from 'aws-sdk'
export default class OrderRepository {
constructor(
private readonly httpService: HttpService,
private readonly sns: AWS.SNS,
) {
if (!process.env.FETCH_ORDER_URL) {
throw new Error('Missing FETCH_ORDER_URL environment var')
}
if (!process.env.ORDER_API_KEY) {
throw new Error('Missing ORDER_API_KEY environment var')
}
if (!process.env.SNS_ERROR_TOPIC) {
throw new Error('Missing SNS_ERROR_TOPIC environment var')
}
}
public async fetchOrderByOrderId(
orderId: string,
status: string,
): Promise<OrderInterface> {
try {
const response: AxiosResponse = await this.httpService.get(
process.env.FETCH_ORDER_URL as string,
{
params: {
orderId,
orderStatus: status,
},
headers: {
'X-API-Key': process.env.ORDER_API_KEY,
},
},
)
if (
response.data.code !== 200 ||
response.data.message !== 'success' ||
!response.data.data.length
) {
throw new Error('Response is missing mandatory fields')
}
return response.data.data[0]
} catch (exception) {
const message: string = `Unable to fetch order by orderId ${orderId}. Exception: ${
exception instanceof Error
? exception.message
: JSON.stringify(exception)
} Arguments: ${JSON.stringify(arguments)}`
await this.sns
.publish({
Message: message,
TopicArn: process.env.SNS_ERROR_TOPIC,
})
.promise()
throw new Error(message)
}
}
public async fetchOrderByProductId(
productId: string,
status: string,
): Promise<OrderInterface> {
try {
const response: AxiosResponse = await this.httpService.get(
process.env.FETCH_ORDER_URL as string,
{
params: {
productId,
orderStatus: status,
},
headers: {
'X-API-Key': process.env.ORDER_API_KEY,
},
},
)
if (
response.data.code !== 200 ||
response.data.message !== 'success' ||
!response.data.data.length
) {
throw new Error('Response is missing mandatory fields')
}
return response.data.data[0]
} catch (exception) {
const message: string = `Unable to fetch order by productId ${productId}. Exception: ${
exception instanceof Error
? exception.message
: JSON.stringify(exception)
} Arguments: ${JSON.stringify(arguments)}`
await this.sns
.publish({
Message: message,
TopicArn: process.env.SNS_ERROR_TOPIC,
})
.promise()
throw new Error(message)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment