UNPKG

1.93 kBJavaScriptView Raw
1(function (define) {
2
3 define(['../rest', './interceptor/errorCode', './interceptor/mime', './interceptor/entity', './interceptor/pathPrefix', 'when'], function (client, errorCode, mime, entity, pathPrefix, when) {
4
5 var plugin;
6
7 function parseConfig(name, refObj) {
8 return {
9 prefix: name,
10 mime: refObj.mime,
11 accept: refObj.accept,
12 errorCode: refObj.errorCode,
13 entity: refObj.entity
14 };
15 }
16
17 /**
18 * Builds the rest client for the provided config
19 *
20 * @param client the client to wrap
21 * @param config configuration for client interceptors
22 */
23 function buildClient(client, config) {
24 return when(client, function (client) {
25 if (config.errorCode !== false) {
26 client = errorCode(client, { code: config.errorCode });
27 }
28 if (config.mime !== false) {
29 client = mime(client, { mime: config.mime || 'application/x-www-form-urlencoded', accept: config.accept });
30 }
31 if (config.entity !== false) {
32 client = entity(client);
33 }
34 client = pathPrefix(client, { prefix: config.prefix });
35 return client;
36 });
37 }
38
39 /**
40 * Resolves a 'rest' client for the specified path and scopes, e.g. client!url/to/resource
41 *
42 * @param resolver
43 * @param name
44 * @param refObj
45 * @param wire
46 */
47 function resolveClient(resolver, name, refObj, wire) {
48 var config, client;
49
50 config = parseConfig(name, refObj);
51 client = buildClient(refObj.client, config);
52
53 when(client, resolver.resolve, resolver.reject);
54 }
55
56 /**
57 * The plugin instance. Can be the same for all wiring runs
58 */
59 plugin = {
60 resolvers: {
61 client: resolveClient
62 }
63 };
64
65 return {
66 wire$plugin: function restPlugin(/* ready, destroyed, options */) {
67 return plugin;
68 }
69 };
70
71 });
72
73}(
74 typeof define === 'function' ? define : function (deps, factory) {
75 module.exports = factory.apply(this, deps.map(require));
76 }
77 // Boilerplate for AMD and Node
78));