This repository has been archived by the owner on Jan 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathng-contentful.js
101 lines (87 loc) · 2.85 KB
/
ng-contentful.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
'use strict';
(function(){
var module = angular.module('ng-contentful', []);
module.provider('contentfulClient', function ContentfulClientProvider() {
var spaceId, accessToken, ssl=true, options= {};
this.setSpaceId = function (id) { spaceId = id; };
this.setAccessToken = function (token) { accessToken = token; };
this.setSSL = function (useSSL) { ssl = !!useSSL; };
this.setOptions = function (opt) { options = opt; };
this.$get = ['$q', function ($q) {
/*global contentful*/
var finalOptions = Object.create(options);
finalOptions.space = spaceId;
finalOptions.accessToken = accessToken;
finalOptions.secure = ssl;
var client = contentful.createClient(finalOptions);
pimpPromises(client, 'asset assets contentType contentTypes entry entries space'.split(' '));
return client;
function pimpPromises(object, methods) {
methods.forEach(function (method) {
var originalMethod = object[method];
object[method] = function () {
var args = arguments;
return $q.when(originalMethod.apply(object, args));
};
});
}
}];
});
module.factory('ContentTypeList', ['$q', 'contentfulClient', function ($q, contentfulClient) {
var cache = {};
var lookups = {};
return {
lookupContentType: function (id) {
if (cache[id]) {
return $q.when(cache[id]);
} else if (lookups[id]) {
return lookups[id];
} else {
var lookup = contentfulClient.contentType(id)
.then(function (contentType) {
cache[id] = contentType;
return contentType;
});
lookups[id] = lookup;
return lookup;
}
},
loadAllContentTypes: function () {
contentfulClient.contentTypes()
.then(function (contentTypes) {
contentTypes.forEach(function (contentType) {
cache[contentType.sys.id] = contentType;
});
});
},
getContentType: function (id) {
return cache[id];
}
};
}]);
module.controller('EntryController', ['$scope', 'ContentTypeList', function ($scope, ContentTypeList) {
$scope.entryTitle = function () {
var contentType = getContentType();
if (contentType) {
return $scope.entry.fields[contentType.displayField];
}
};
$scope.contentType = function () {
return getContentType();
};
function lookupContentType() {
return ContentTypeList.lookupContentType(contentTypeId());
}
function getContentType() {
var ct = ContentTypeList.getContentType(contentTypeId());
if (ct) {
return ct;
} else {
lookupContentType();
}
}
function contentTypeId() {
return $scope.entry.sys.contentType.sys.id;
}
}]);
})();