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.
17 // The purpose of the `Content` object is to abstract away the data conversions
18 // to and from raw content entities as strings. For example, you want to be able
19 // to pass in a Javascript object and have it be automatically converted into a
20 // JSON string if the `content-type` is set to a JSON-based media type.
21 // Conversely, you want to be able to transparently get back a Javascript object
22 // in the response if the `content-type` is a JSON-based media-type.
24 // One limitation of the current implementation is that it [assumes the `charset` is UTF-8](https://github.com/spire-io/shred/issues/5).
26 // The `Content` constructor takes an options object, which *must* have either a
27 // `body` or `data` property and *may* have a `type` property indicating the
28 // media type. If there is no `type` attribute, a default will be inferred.
29 var Content = function(options) {
30 this.body = options.body;
31 this.data = options.data;
32 this.type = options.type;
36 // Treat `toString()` as asking for the `content.body`. That is, the raw content entity.
38 // toString: function() { return this.body; }
40 // Commented out, but I've forgotten why. :/
44 // `Content` objects have the following attributes:
45 Object.defineProperties(Content.prototype,{
47 // - **type**. Typically accessed as `content.type`, reflects the `content-type`
48 // header associated with the request or response. If not passed as an options
49 // to the constructor or set explicitly, it will infer the type the `data`
50 // attribute, if possible, and, failing that, will default to `text/plain`.
57 switch(typeof this._data) {
58 case "string": return "text/plain";
59 case "object": return "application/json";
65 set: function(value) {
72 // - **data**. Typically accessed as `content.data`, reflects the content entity
73 // converted into Javascript data. This can be a string, if the `type` is, say,
74 // `text/plain`, but can also be a Javascript object. The conversion applied is
75 // based on the `processor` attribute. The `data` attribute can also be set
76 // directly, in which case the conversion will be done the other way, to infer
77 // the `body` attribute.
81 return this.processor.parser(this._body);
87 if (this._body&&data) Errors.setDataWithBody(this);
94 // - **body**. Typically accessed as `content.body`, reflects the content entity
95 // as a UTF-8 string. It is the mirror of the `data` attribute. If you set the
96 // `data` attribute, the `body` attribute will be inferred and vice-versa. If
97 // you attempt to set both, an exception is raised.
101 return this.processor.stringify(this._data);
103 return this._body.toString();
106 set: function(body) {
107 if (this._data&&body) Errors.setBodyWithData(this);
114 // - **processor**. The functions that will be used to convert to/from `data` and
115 // `body` attributes. You can add processors. The two that are built-in are for
116 // `text/plain`, which is basically an identity transformation and
117 // `application/json` and other JSON-based media types (including custom media
118 // types with `+json`). You can add your own processors. See below.
121 var processor = Content.processors[this.type];
125 // Return the first processor that matches any part of the
126 // content type. ex: application/vnd.foobar.baz+json will match json.
127 var main = this.type.split(";")[0];
128 var parts = main.split(/\+|\//);
129 for (var i=0, l=parts.length; i < l; i++) {
130 processor = Content.processors[parts[i]]
132 return processor || {parser:identity,stringify:toString};
138 // - **length**. Typically accessed as `content.length`, returns the length in
139 // bytes of the raw content entity.
142 if (typeof Buffer !== 'undefined') {
143 return Buffer.byteLength(this.body);
145 return this.body.length;
150 Content.processors = {};
152 // The `registerProcessor` function allows you to add your own processors to
153 // convert content entities. Each processor consists of a Javascript object with
155 // - **parser**. The function used to parse a raw content entity and convert it
156 // into a Javascript data type.
157 // - **stringify**. The function used to convert a Javascript data type into a
158 // raw content entity.
159 Content.registerProcessor = function(types,processor) {
161 // You can pass an array of types that will trigger this processor, or just one.
162 // We determine the array via duck-typing here.
164 types.forEach(function(type) {
165 Content.processors[type] = processor;
168 // If you didn't pass an array, we just use what you pass in.
169 Content.processors[types] = processor;
173 // Register the identity processor, which is used for text-based media types.
174 var identity = function(x) { return x; }
175 , toString = function(x) { return x.toString(); }
176 Content.registerProcessor(
177 ["text/html","text/plain","text"],
178 { parser: identity, stringify: toString });
180 // Register the JSON processor, which is used for JSON-based media types.
181 Content.registerProcessor(
182 ["application/json; charset=utf-8","application/json","json"],
184 parser: function(string) {
185 return JSON.parse(string);
187 stringify: function(data) {
188 return JSON.stringify(data); }});
190 var qs = require('querystring');
191 // Register the post processor, which is used for JSON-based media types.
192 Content.registerProcessor(
193 ["application/x-www-form-urlencoded"],
194 { parser : qs.parse, stringify : qs.stringify });
196 // Error functions are defined separately here in an attempt to make the code
199 setDataWithBody: function(object) {
200 throw new Error("Attempt to set data attribute of a content object " +
201 "when the body attributes was already set.");
203 setBodyWithData: function(object) {
204 throw new Error("Attempt to set body attribute of a content object " +
205 "when the data attributes was already set.");
208 module.exports = Content;