-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import getProtoData from './getProtoData' | ||
import PouchFactory from '../models/PouchFactory' | ||
import BaseEntity from '../models/BaseEntity' | ||
|
||
export function belongsToMapper<S>(target: any, keyName: string) { | ||
return (factory: PouchFactory<S>): Promise<BaseEntity<S>> => { | ||
const { rels } = getProtoData(target) | ||
|
||
const rel = rels.find(({ key }) => key === keyName) | ||
|
||
if (!rel) { | ||
throw new Error(`No relation available for ${keyName}`) | ||
} | ||
|
||
if ('belongsTo' in rel) { | ||
return rel.belongsTo().findById(factory, target[keyName]) | ||
} | ||
|
||
throw new Error('Unsupported relation') | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { belongsToMapper } from '../../../src/utils/relationMappers' | ||
import emptyProtoData from '../../utils/emptyProtoData' | ||
|
||
describe('belongsToMapper', () => { | ||
test('Throws error if no relation available', () => { | ||
const mapper = belongsToMapper({ __protoData: emptyProtoData({}) }, 'foo') | ||
|
||
expect(() => mapper(null)).toThrowError(/No relation available/) | ||
}) | ||
|
||
test('Throws an error for unsupported relation', () => { | ||
const mapper = belongsToMapper( | ||
{ | ||
__protoData: emptyProtoData({ | ||
rels: [ | ||
{ | ||
unsupported: 'foo', | ||
key: 'foo' | ||
} as any | ||
] | ||
}) | ||
}, | ||
'foo' | ||
) | ||
|
||
expect(() => mapper(null)).toThrowError(/Unsupported/) | ||
}) | ||
}) |