| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- class Headers {
- constructor(init = {}) {
- this._headers = {};
-
- if (init instanceof Headers) {
- // 如果传入的是另一个 Headers 实例,复制其内容
- init.forEach((value, name) => {
- this.append(name, value);
- });
- } else if (init) {
- // 处理普通对象或数组
- Object.entries(init).forEach(([name, value]) => {
- if (Array.isArray(value)) {
- // 处理数组值(如 ['value1', 'value2'])
- value.forEach(v => this.append(name, v));
- } else {
- this.set(name, value);
- }
- });
- }
- }
-
- // 添加头(可重复添加同名头)
- append(name, value) {
- const normalizedName = this._normalizeName(name);
- if (this._headers[normalizedName]) {
- this._headers[normalizedName] += `, ${value}`;
- } else {
- this._headers[normalizedName] = String(value);
- }
- }
-
- // 设置头(覆盖同名头)
- set(name, value) {
- this._headers[this._normalizeName(name)] = String(value);
- }
-
- // 获取头
- get(name) {
- return this._headers[this._normalizeName(name)] || null;
- }
-
- // 检查是否存在头
- has(name) {
- return this._normalizeName(name) in this._headers;
- }
-
- // 删除头
- delete(name) {
- delete this._headers[this._normalizeName(name)];
- }
-
- // 遍历头
- forEach(callback) {
- Object.entries(this._headers).forEach(([name, value]) => {
- callback(value, name, this);
- });
- }
-
- // 获取所有头(原始对象)
- raw() {
- return { ...this._headers };
- }
-
- // 规范化头名称(转为小写)
- _normalizeName(name) {
- if (typeof name !== 'string') {
- throw new TypeError('Header name must be a string');
- }
- return name.toLowerCase();
- }
- }
-
- // 全局注册(如果需要)
- if (typeof globalThis.Headers === 'undefined') {
- globalThis.Headers = Headers;
- }
-
- export default Headers;
|