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(open-payments): add list incoming payments #851

Merged
merged 7 commits into from
Jan 9, 2023
Merged
218 changes: 218 additions & 0 deletions packages/open-payments/src/client/incoming-payment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
completeIncomingPayment,
createIncomingPayment,
createIncomingPaymentRoutes,
listIncomingPayment,
getIncomingPayment,
validateCompletedIncomingPayment,
validateCreatedIncomingPayment,
Expand All @@ -13,10 +14,22 @@ import {
defaultAxiosInstance,
mockILPStreamConnection,
mockIncomingPayment,
mockIncomingPaymentPaginationResult,
mockOpenApiResponseValidators,
silentLogger
} from '../test/helpers'
import nock from 'nock'
import { v4 as uuid } from 'uuid'
import * as requestors from './requests'
import { getRSPath } from '../types'

jest.mock('./requests', () => {
return {
// https://jestjs.io/docs/jest-object#jestmockmodulename-factory-options
__esModule: true,
...jest.requireActual('./requests')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can mock out the get here, so we don't need to .mockResolvedValueOnce(incomingPaymentPaginationResult) on the getSpy below

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also think we can remove __esModule: true, because we aren't using a default export

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can mock out the get here, so we don't need to .mockResolvedValueOnce(incomingPaymentPaginationResult) on the getSpy below

If we mock the get, all the tests that are using it will fail:

Test Suites: 1 failed, 1 total
Tests:       8 failed, 26 passed, 34 total

image


I also think we can remove __esModule: true, because we aren't using a default export

When __esModule: true is not specified, we get the following error:

incoming-payment › routes › list › calls get method with correct validator

    Error when making Open Payments GET request: Nock: No match for request {
      "method": "GET",
      "url": "http://localhost:1000/.well-known/pay/incoming-payments",
      "headers": {
        "accept": "application/json, text/plain, */*",
        "content-type": "application/json",
        "authorization": "GNAP accessToken",
        "signature": "sig1=:VYmcFqf6cSzLN10+dG/TnXQI23FxWY/n2/wVbNW4oX+U4rCBHpbT75AaMZOe3qzoUDiQUxZg0fpXjSBxHkNpDw==:",
        "signature-input": "sig1=(\"@method\" \"@target-uri\" \"authorization\");created=1671199508;keyid=\"default-key-id\";alg=\"ed25519\"",
        "user-agent": "axios/1.1.2",
        "accept-encoding": "gzip, deflate, br"
      }
    }

}
})

describe('incoming-payment', (): void => {
let openApi: OpenAPI
Expand Down Expand Up @@ -74,6 +87,21 @@ describe('incoming-payment', (): void => {
method: HttpMethod.POST
})
})

test('creates listIncomingPaymentsOpenApiValidator', async (): Promise<void> => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@raducristianpopa can we try testing that the list route calls the proper validator, similar to this test? https://github.com/interledger/rafiki/pull/848/files#diff-4f318c2a374cc145f8825fecf95d77b29a728927b5a64ce393897b01becb2b93R37-R38

If it takes too long, I'm going to approve the PR anyway so we can merge it later and working on these route tests at a separate time

jest.spyOn(openApi, 'createResponseValidator')

createIncomingPaymentRoutes({
axiosInstance,
openApi,
logger
})

expect(openApi.createResponseValidator).toHaveBeenCalledWith({
path: '/incoming-payments',
method: HttpMethod.GET
})
})
})

describe('getIncomingPayment', (): void => {
Expand Down Expand Up @@ -322,6 +350,156 @@ describe('incoming-payment', (): void => {
})
})

describe('listIncomingPayment', (): void => {
const paymentPointer = `${baseUrl}/.well-known/pay`

describe('forward pagination', (): void => {
test.each`
first | cursor
${undefined} | ${undefined}
${1} | ${undefined}
${5} | ${uuid()}
`(
'returns incoming payments list',
async ({ first, cursor }): Promise<void> => {
const incomingPaymentPaginationResult =
mockIncomingPaymentPaginationResult({
result: Array(first).fill(mockIncomingPayment())
})

const scope = nock(paymentPointer)
.get('/incoming-payments')
.query({
...(first ? { first } : {}),
...(cursor ? { cursor } : {})
})
.reply(200, incomingPaymentPaginationResult)

const result = await listIncomingPayment(
{
axiosInstance,
logger
},
{
paymentPointer,
accessToken: 'accessToken'
},
openApiValidators.successfulValidator,
{
first,
cursor
}
)

expect(result).toStrictEqual(incomingPaymentPaginationResult)
scope.done()
}
)
})

describe('backward pagination', (): void => {
test.each`
last | cursor
${undefined} | ${uuid()}
${5} | ${uuid()}
Comment on lines +402 to +406
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is setup correctly, but in general makes me confused about the backward pagination parameters.

If we only provide a cursor, like (backwards-pagination allows) then by default we will end up forwards paginating, based on this code in the backend:

export function parsePaginationQueryParameters({
first,
last,
cursor
}: PageQueryParams): Pagination {
return {
first,
last,
before: last ? cursor : undefined,
after: cursor && !last ? cursor : undefined
}
}

would this mean that we should make last required as well in Open Payments API? Only cursor is required:

image

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

@mkurapov mkurapov Dec 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm in favour of not supporting both parameters (for now) to make the Open Payments pagination type simple & similar to what you describe in comment:

after + count || before + count || count (default forward pagination)

`(
'returns incoming payments list',
async ({ last, cursor }): Promise<void> => {
const incomingPaymentPaginationResult =
mockIncomingPaymentPaginationResult({
result: Array(last).fill(mockIncomingPayment())
})

const scope = nock(paymentPointer)
.get('/incoming-payments')
.query({
...(last ? { last } : {}),
cursor
})
.reply(200, incomingPaymentPaginationResult)

const result = await listIncomingPayment(
{
axiosInstance,
logger
},
{
paymentPointer,
accessToken: 'accessToken'
},
openApiValidators.successfulValidator,
{
last,
cursor
}
)

expect(result).toStrictEqual(incomingPaymentPaginationResult)
scope.done()
}
)
})

test('throws if an incoming payment does not pass validation', async (): Promise<void> => {
const incomingPayment = mockIncomingPayment({
incomingAmount: {
assetCode: 'USD',
assetScale: 2,
value: '10'
},
receivedAmount: {
assetCode: 'USD',
assetScale: 4,
value: '0'
}
})

const incomingPaymentPaginationResult =
mockIncomingPaymentPaginationResult({
result: [incomingPayment]
})

const scope = nock(paymentPointer)
.get('/incoming-payments')
.reply(200, incomingPaymentPaginationResult)

await expect(() =>
listIncomingPayment(
{
axiosInstance,
logger
},
{
paymentPointer,
accessToken: 'accessToken'
},
openApiValidators.successfulValidator
)
).rejects.toThrow('Could not validate incoming payment')

scope.done()
})

test('throws if an incoming payment does not pass open api validation', async (): Promise<void> => {
const incomingPaymentPaginationResult =
mockIncomingPaymentPaginationResult()

const scope = nock(paymentPointer)
.get('/incoming-payments')
.reply(200, incomingPaymentPaginationResult)

await expect(() =>
listIncomingPayment(
{ axiosInstance, logger },
{ paymentPointer, accessToken: 'accessToken' },
openApiValidators.failedValidator
)
).rejects.toThrowError()

scope.done()
})
})

describe('validateIncomingPayment', (): void => {
test('returns incoming payment if passes validation', async (): Promise<void> => {
const incomingPayment = mockIncomingPayment({
Expand Down Expand Up @@ -536,4 +714,44 @@ describe('incoming-payment', (): void => {
)
})
})

describe('routes', (): void => {
describe('list', (): void => {
test('calls get method with correct validator', async (): Promise<void> => {
const mockResponseValidator = ({ path, method }) =>
path === '/incoming-payments' && method === HttpMethod.GET

const incomingPaymentPaginationResult =
mockIncomingPaymentPaginationResult({
result: [mockIncomingPayment()]
})
const paymentPointer = `${baseUrl}/.well-known/pay`
const url = `${paymentPointer}${getRSPath('/incoming-payments')}`

jest
.spyOn(openApi, 'createResponseValidator')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.mockImplementation(mockResponseValidator as any)

const getSpy = jest
.spyOn(requestors, 'get')
.mockResolvedValueOnce(incomingPaymentPaginationResult)

await createIncomingPaymentRoutes({
openApi,
axiosInstance,
logger
}).list({ paymentPointer, accessToken: 'accessToken' })

expect(getSpy).toHaveBeenCalledWith(
{
axiosInstance,
logger
},
{ url, accessToken: 'accessToken' },
true
)
})
})
})
})
72 changes: 71 additions & 1 deletion packages/open-payments/src/client/incoming-payment.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { HttpMethod, ResponseValidator } from 'openapi'
import { BaseDeps, RouteDeps } from '.'
import { IncomingPayment, getRSPath, CreateIncomingPaymentArgs } from '../types'
import {
IncomingPayment,
getRSPath,
CreateIncomingPaymentArgs,
PaginationArgs,
IncomingPaymentPaginationResult
} from '../types'
import { get, post } from './requests'

interface GetArgs {
Expand All @@ -14,10 +20,19 @@ interface PostArgs<T = undefined> {
accessToken: string
}

interface ListGetArgs {
paymentPointer: string
accessToken: string
}

export interface IncomingPaymentRoutes {
get(args: GetArgs): Promise<IncomingPayment>
create(args: PostArgs<CreateIncomingPaymentArgs>): Promise<IncomingPayment>
complete(args: PostArgs): Promise<IncomingPayment>
list(
args: ListGetArgs,
pagination?: PaginationArgs
): Promise<IncomingPaymentPaginationResult>
}

export const createIncomingPaymentRoutes = (
Expand All @@ -43,6 +58,12 @@ export const createIncomingPaymentRoutes = (
method: HttpMethod.POST
})

const listIncomingPaymentOpenApiValidator =
openApi.createResponseValidator<IncomingPaymentPaginationResult>({
path: getRSPath('/incoming-payments'),
method: HttpMethod.GET
})

return {
get: (args: GetArgs) =>
getIncomingPayment(
Expand All @@ -61,6 +82,13 @@ export const createIncomingPaymentRoutes = (
{ axiosInstance, logger },
args,
completeIncomingPaymentOpenApiValidator
),
list: (args: ListGetArgs, pagination?: PaginationArgs) =>
listIncomingPayment(
{ axiosInstance, logger },
args,
listIncomingPaymentOpenApiValidator,
pagination
)
}
}
Expand Down Expand Up @@ -137,6 +165,48 @@ export const completeIncomingPayment = async (
}
}

export const listIncomingPayment = async (
deps: BaseDeps,
args: ListGetArgs,
validateOpenApiResponse: ResponseValidator<IncomingPaymentPaginationResult>,
pagination?: PaginationArgs
) => {
const { axiosInstance, logger } = deps
const { accessToken, paymentPointer } = args

const url = `${paymentPointer}${getRSPath('/incoming-payments')}`

const incomingPayments = await get(
{ axiosInstance, logger },
{
url,
accessToken,
...(pagination ? { queryParams: { ...pagination } } : {})
},
validateOpenApiResponse
)

for (const incomingPayment of incomingPayments.result) {
try {
validateIncomingPayment(incomingPayment)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For list responses, we could validate that pagination.hasPreviousPage is false if cursor was not specified (which should be forward pagination from the start).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly agree, but I'm not sure it's worth failing the whole request over it, however.

} catch (error) {
const errorMessage = 'Could not validate incoming payment'
logger.error(
{
url,
validateError: error?.message,
incomingPaymentId: incomingPayment.id
},
errorMessage
)

throw new Error(errorMessage)
}
}

return incomingPayments
}

export const validateIncomingPayment = (
payment: IncomingPayment
): IncomingPayment => {
Expand Down
21 changes: 21 additions & 0 deletions packages/open-payments/src/test/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
NonInteractiveGrant,
OutgoingPayment,
OutgoingPaymentPaginationResult,
IncomingPaymentPaginationResult,
AccessToken
} from '../types'
import base64url from 'base64url'
Expand Down Expand Up @@ -71,6 +72,26 @@ export const mockIncomingPayment = (
...overrides
})

export const mockIncomingPaymentPaginationResult = (
overrides?: Partial<IncomingPaymentPaginationResult>
): IncomingPaymentPaginationResult => {
const result = overrides?.result || [
mockIncomingPayment(),
mockIncomingPayment(),
mockIncomingPayment()
]

return {
result,
pagination: overrides?.pagination || {
startCursor: result[0].id,
hasNextPage: true,
hasPreviousPage: true,
endCursor: result[result.length - 1].id
}
}
}

export const mockOutgoingPayment = (
overrides?: Partial<OutgoingPayment>
): OutgoingPayment => ({
Expand Down
Loading