Skip to content

Commit d144b7f

Browse files
committed
fix(args2request): fix args convertion to request when there is a entity on the use case request
1 parent d79992b commit d144b7f

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/args2request.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
1+
const { entity, tryParse } = require('@herbsjs/herbs')
2+
13
function args2request(args, useCase, _info) {
24
const isMutation = _info?.operation?.operation === 'mutation'
35
if (isMutation && args?.input) args = args.input
46
const params = {}
57
const fields = Object.keys(useCase.requestSchema)
6-
for (const field of fields) params[field] = args[field]
8+
for (const field of fields) {
9+
const name = field
10+
const type = useCase.requestSchema[field]
11+
params[name] = parametersCast(args[name], type)
12+
}
713
return params
814
}
915

16+
function parametersCast(value, type) {
17+
if (Array.isArray(type)) return value?.map(item => defaultConvention.parametersCast(item, type[0]))
18+
if (entity.isEntity(type) && value) return type.fromJSON(value)
19+
return tryParse(value, type)
20+
}
21+
1022
module.exports = args2request

test/defaultResolver.test.js

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const assert = require('assert')
2-
const { Ok, usecase, step, Err } = require('@herbsjs/herbs')
2+
const { entity, field, usecase, step, request, Ok, Err } = require('@herbsjs/herbs')
33
const defaultResolver = require('../src/defaultResolver')
44

55
describe('GraphQL - Default Resolver', () => {
@@ -43,6 +43,37 @@ describe('GraphQL - Default Resolver', () => {
4343
assert.deepStrictEqual(ret, { id: 1 })
4444
})
4545

46+
it('should resolve a mutation with complex request and run a use case', async () => {
47+
// Given
48+
const AnEntity = entity('An Entity', {
49+
id: field(Number),
50+
field1: field(String)
51+
})
52+
53+
const AnComplexEntity = entity('An Complex Entity', {
54+
id: field(Number),
55+
field1: field(String),
56+
entity1: field(AnEntity)
57+
})
58+
59+
const AUseCase = () =>
60+
usecase('Use Case X', {
61+
request: request.from(AnComplexEntity),
62+
response: Number,
63+
authorize: async () => Ok(),
64+
'Step 1': step((ctx) => { return Ok(ctx.ret = ctx.req) }
65+
)
66+
})
67+
68+
const resolver = defaultResolver(AUseCase)
69+
70+
// When
71+
const ret = await resolver(null, { input: { id: 1, field1: 'xyz', field2: 123, entity1: { id: 1 } } }, { user: {} }, { operation: { operation: 'mutation' } })
72+
73+
// Then
74+
assert.deepStrictEqual(JSON.parse(JSON.stringify(ret)), { id: 1, field1: 'xyz', entity1: { id: 1 } })
75+
})
76+
4677
it('should not run a use case if not autorized and throw a ForbiddenError', async () => {
4778
// Given
4879
const AUseCase = {

0 commit comments

Comments
 (0)