next
Version:
The React Framework
100 lines (99 loc) • 3.1 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
var _nextUrl = require("../next-url");
var _utils = require("../utils");
var _cookie = _interopRequireDefault(require("next/dist/compiled/cookie"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const INTERNALS = Symbol('internal response');
const REDIRECTS = new Set([
301,
302,
303,
307,
308
]);
class NextResponse extends Response {
constructor(body, init = {}){
var ref, ref1, ref2;
super(body, init);
const cookieParser = ()=>{
const value = this.headers.get('cookie');
return value ? _cookie.default.parse(value) : {};
};
this[INTERNALS] = {
cookieParser,
url: init.url ? new _nextUrl.NextURL(init.url, {
basePath: (ref = init.nextConfig) === null || ref === void 0 ? void 0 : ref.basePath,
i18n: (ref1 = init.nextConfig) === null || ref1 === void 0 ? void 0 : ref1.i18n,
trailingSlash: (ref2 = init.nextConfig) === null || ref2 === void 0 ? void 0 : ref2.trailingSlash,
headers: (0, _utils).toNodeHeaders(this.headers)
}) : undefined
};
}
get cookies() {
return this[INTERNALS].cookieParser();
}
cookie(name, value, opts = {}) {
const val = typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value);
const options = {
...opts
};
if (options.maxAge) {
options.expires = new Date(Date.now() + options.maxAge);
options.maxAge /= 1000;
}
if (options.path == null) {
options.path = '/';
}
this.headers.append('Set-Cookie', _cookie.default.serialize(name, String(val), options));
return this;
}
clearCookie(name, opts = {}) {
return this.cookie(name, '', {
expires: new Date(1),
path: '/',
...opts
});
}
static json(body) {
return new NextResponse(JSON.stringify(body), {
headers: {
'content-type': 'application/json'
}
});
}
static redirect(url, status = 307) {
if (!REDIRECTS.has(status)) {
throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
}
const destination = (0, _utils).validateURL(url);
return new NextResponse(destination, {
headers: {
Location: destination
},
status
});
}
static rewrite(destination) {
return new NextResponse(null, {
headers: {
'x-middleware-rewrite': (0, _utils).validateURL(destination)
}
});
}
static next() {
return new NextResponse(null, {
headers: {
'x-middleware-next': '1'
}
});
}
}
exports.NextResponse = NextResponse;
//# sourceMappingURL=response.js.map
;