2 * Copyright 2016 ZTE Corporation.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 // The purpose of the `Content` object is to abstract away the data conversions
17 // to and from raw content entities as strings. For example, you want to be able
18 // to pass in a Javascript object and have it be automatically converted into a
19 // JSON string if the `content-type` is set to a JSON-based media type.
20 // Conversely, you want to be able to transparently get back a Javascript object
21 // in the response if the `content-type` is a JSON-based media-type.
23 // One limitation of the current implementation is that it [assumes the `charset` is UTF-8](https://github.com/spire-io/shred/issues/5).
25 // The `Content` constructor takes an options object, which *must* have either a
26 // `body` or `data` property and *may* have a `type` property indicating the
27 // media type. If there is no `type` attribute, a default will be inferred.
28 var Content = function(options) {
29 this.body = options.body;
30 this.data = options.data;
31 this.type = options.type;
35 // Treat `toString()` as asking for the `content.body`. That is, the raw content entity.
37 // toString: function() { return this.body; }
39 // Commented out, but I've forgotten why. :/
43 // `Content` objects have the following attributes:
44 Object.defineProperties(Content.prototype,{
46 // - **type**. Typically accessed as `content.type`, reflects the `content-type`
47 // header associated with the request or response. If not passed as an options
48 // to the constructor or set explicitly, it will infer the type the `data`
49 // attribute, if possible, and, failing that, will default to `text/plain`.
56 switch(typeof this._data) {
57 case "string": return "text/plain";
58 case "object": return "application/json";
64 set: function(value) {
71 // - **data**. Typically accessed as `content.data`, reflects the content entity
72 // converted into Javascript data. This can be a string, if the `type` is, say,
73 // `text/plain`, but can also be a Javascript object. The conversion applied is
74 // based on the `processor` attribute. The `data` attribute can also be set
75 // directly, in which case the conversion will be done the other way, to infer
76 // the `body` attribute.
80 return this.processor.parser(this._body);
86 if (this._body&&data) Errors.setDataWithBody(this);
93 // - **body**. Typically accessed as `content.body`, reflects the content entity
94 // as a UTF-8 string. It is the mirror of the `data` attribute. If you set the
95 // `data` attribute, the `body` attribute will be inferred and vice-versa. If
96 // you attempt to set both, an exception is raised.
100 return this.processor.stringify(this._data);
102 return this._body.toString();
105 set: function(body) {
106 if (this._data&&body) Errors.setBodyWithData(this);
113 // - **processor**. The functions that will be used to convert to/from `data` and
114 // `body` attributes. You can add processors. The two that are built-in are for
115 // `text/plain`, which is basically an identity transformation and
116 // `application/json` and other JSON-based media types (including custom media
117 // types with `+json`). You can add your own processors. See below.
120 var processor = Content.processors[this.type];
124 // Return the first processor that matches any part of the
125 // content type. ex: application/vnd.foobar.baz+json will match json.
126 var main = this.type.split(";")[0];
127 var parts = main.split(/\+|\//);
128 for (var i=0, l=parts.length; i < l; i++) {
129 processor = Content.processors[parts[i]]
131 return processor || {parser:identity,stringify:toString};
137 // - **length**. Typically accessed as `content.length`, returns the length in
138 // bytes of the raw content entity.
141 if (typeof Buffer !== 'undefined') {
142 return Buffer.byteLength(this.body);
144 return this.body.length;
149 Content.processors = {};
151 // The `registerProcessor` function allows you to add your own processors to
152 // convert content entities. Each processor consists of a Javascript object with
154 // - **parser**. The function used to parse a raw content entity and convert it
155 // into a Javascript data type.
156 // - **stringify**. The function used to convert a Javascript data type into a
157 // raw content entity.
158 Content.registerProcessor = function(types,processor) {
160 // You can pass an array of types that will trigger this processor, or just one.
161 // We determine the array via duck-typing here.
163 types.forEach(function(type) {
164 Content.processors[type] = processor;
167 // If you didn't pass an array, we just use what you pass in.
168 Content.processors[types] = processor;
172 // Register the identity processor, which is used for text-based media types.
173 var identity = function(x) { return x; }
174 , toString = function(x) { return x.toString(); }
175 Content.registerProcessor(
176 ["text/html","text/plain","text"],
177 { parser: identity, stringify: toString });
179 // Register the JSON processor, which is used for JSON-based media types.
180 Content.registerProcessor(
181 ["application/json; charset=utf-8","application/json","json"],
183 parser: function(string) {
184 return JSON.parse(string);
186 stringify: function(data) {
187 return JSON.stringify(data); }});
189 var qs = require('querystring');
190 // Register the post processor, which is used for JSON-based media types.
191 Content.registerProcessor(
192 ["application/x-www-form-urlencoded"],
193 { parser : qs.parse, stringify : qs.stringify });
195 // Error functions are defined separately here in an attempt to make the code
198 setDataWithBody: function(object) {
199 throw new Error("Attempt to set data attribute of a content object " +
200 "when the body attributes was already set.");
202 setBodyWithData: function(object) {
203 throw new Error("Attempt to set body attribute of a content object " +
204 "when the data attributes was already set.");
207 module.exports = Content;