npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@pagoda-tools/cos

v1.0.11

Published

针对腾讯 COS JS SDK `cos-js-sdk-v5`,二次封装工具。

Downloads

48

Readme

@pagoda-tools/cos

针对腾讯 COS JS SDK cos-js-sdk-v5,二次封装工具。

安装

yarn add @pagoda-tools/cos

初始化

Note:

  1. 参数 cosOptions: 查看 cos 初始化
//
import { PagodaCos } from '@pagoda-tools/cos';
const cosOptions = {
  // ...
};
const pdOptions = {
  // ...
};

const pagodaCos = new PagodaCOS({
  getConfig() {
    // 调用接口获取相关配置信息
    return Promise.resolve({
      region: 'ap-guangzhou',
      bucket: 'instance-xxxx',
      prefix: 'a1',
    });
  },
  getAuthorization() {
    // 调用接口获取 token 相关鉴权信息
    return Promise.resolve({
      startTime: 1633764822, // 该参数会影响,getObjectUrl Ex
      expiredTime: 1633766622,
      credentials: {
        tmpSecretId: 'xxxxx',
        tmpSecretKey: 'xxxxx',
        sessionToken: 'xxxx',
        ScopeLimit: true,
      },
    });
  },
  cosOptions,
  pdOptions,
});

构造函数参数说明

| 参数名 | 参数描述 | 类型 | 是否必填 | | --- | --- | --- | --- | | getConfig | 获取存储桶配置的回调方法 | Function | 是 | | getAuthorization | 获取签名的回调方法,如果没有SecretIdSecretKey 时,这个参数必选。 注意: 该回调方法在初始化实例时传入,在使用实例调用接口时才会执行并获取签名。,可参考 | Function | 是 | | cosOptions | 腾讯 COS 构造函数参数 | Object | 否 | | pdOptions | PagodaCos 扩展参数 | Object | 否 | | - pdFileHash | 是否对pathhash处理,作用:防止新上传文件覆盖原上传文件,默认false 注意: 在各个上传函数方法中,params.pdFileHash,会独立控制,不与该实例参数的限制。 | boolean | 否 | | - pdCarryFileName | 计算 hash 时,是否携带文件名,默认false | boolean | 否 | | - pdSimplifyHash | 是否简化hash值,默认false 注意: 简化hash既只有 5 位哈希值,最好配合传值path添加时间,如:a1/test/${dayjs().format('YYYYMMDDHHmmss')}/测试文件.[hash].txt | boolean | 否 | | - pdBeforeExpirationTime | 设置过期时间之前判断过期(秒),默认 120 秒,单位:秒 | number | 否 |

开启pdFileHash情况下,传入path的:

  • 默认生成Key格式:test/111.txt ==> ${prefix}/test/[hash].txt
  • pdCarryFileName: true时,生成Key格式,如:test/111.txt ==> ${prefix}/test/111.[hash].txt
  • 如果pdSimplifyHash: false的情况下,原有的hash值,由2a97bec793b2838b6ef8a0652e3fabf4 ==> 1554c,及原长hash简化至 5 位哈希值。

getAuthorization 回调函数说明的函数说明

getAuthorization: function(options) { ... }

getAuthorization 的回调参数说明:

参考腾讯 COS 构造函数参数getAuthorization 说明。

获取完临时密钥后,callback 回传一个对象,回传对象的属性列表如下:

| 属性名 | 参数描述 | 类型 | 是否必填 | | --- | --- | --- | --- | | credentials | 获取证书数据 | Object | 是 | | - tmpSecretId | 获取回来的临时密钥的 tmpSecretId | String | 是 | | - tmpSecretKey | 获取回来的临时密钥的 tmpSecretKey | String | 是 | | - securityToken | 获取回来的临时密钥的 sessionToken,对应 header 的 x-cos-security-token 字段 | String | 是 | | startTime | 密钥获取的开始时间,即获取时刻的时间戳,单位秒,startTime,如:1580000000,用于签名开始时间,传入该参数可避免前端时间偏差签名过期问题 | String | 否 | | expiredTime | 获取回来的临时密钥的 expiredTime,超时时刻的时间戳,单位秒,如:1580000900 | String | 是 |

案例

简单上传文件,适用于小文件上传:建议使用 uploadFile 或 sliceUploadFile 上传

const { Key, Location } = await pagodaCos
  .putObject('test/test1.txt', file, {
    pdFileHash: true,
    onProgress: function (progressData) {
      console.log(JSON.stringify(progressData));
    },
  })
  .catch((err) => {
    console.log(err);
  });
console.log(Key, Location);
/**
 * {
      Key: 'a1/test/test.1554c.txt',
      statusCode: 200,
      headers: {
        'content-length': '0',
        etag: '"2a97bec793b2838b6ef8a0652e3fabf4"',
        'x-cos-request-id': 'NjIxODgxMjhfYTkxMzc2MGJfZjVkMl9hZGQzMzNh'
      },
      Location: 'instance-xxxx.cos.ap-guangzhou.myqcloud.com/a1/test/test.1554c.txt',
      ETag: '"2a97bec793b2838b6ef8a0652e3fabf4"',
      RequestId: 'NjIxODgxMjhfYTkxMzc2MGJfZjVkMl9hZGQzMzNh'
    }
 */

pagodaCos API

实例方法

以下是可用的实例方法。指定的配置将与实例的配置合并。

Note: params参数中大部分参数是继承至腾讯 COS 实例方法中的参数,详细参数请前往腾讯 COS - 上传对象

上传对象

pagodaCos.putObject(path, file, params); // 简单上传
pagodaCos.sliceUploadFile(path, file, params); // 分片上传
pagodaCos.uploadFile(path, file, params); // (推荐) 单文件上传高级接口,会根据SliceSize参数,择优使用 `putObject` 或 'sliceUploadFile' 上传

请求参数

| 属性名 | 参数描述 | 类型 | 是否必填 | | --- | --- | --- | --- | | path | 储存到的子目录 | string | 是 | | file | 上传的文件 | File、Blob、String、ArrayBuffer | 是 | | params | ... | Object | 否 | | - pdFileHash | 同初始实例方法参数一致 | Boolean | 否 | | - ...其它 | 其它参数,前往腾讯 COS 文档,查看实例方法参数说明 | any | 否 |

响应参数(基本一致)

{
  "Key": "a1/test/test.1554c.txt",
  "statusCode": 200,
  "headers": {
    "content-length": "0",
    "etag": "\"2a97bec793b2838b6ef8a0652e3fabf4\"",
    "x-cos-request-id": "NjIxODgxMjhfYTkxMzc2MGJfZjVkMl9hZGQzMzNh"
  },
  "Location": "instance-xxxx.cos.ap-guangzhou.myqcloud.com/a1/test/test.1554c.txt",
  "ETag": "\"2a97bec793b2838b6ef8a0652e3fabf4\"",
  "RequestId": "NjIxODgxMjhfYTkxMzc2MGJfZjVkMl9hZGQzMzNh"
}

pagodaCos.uploadFiles(files[, params])

请求参数

| 属性名 | 参数描述 | 类型 | 是否必填 | | --- | --- | --- | --- | | files | 多文件配置 | Array | 是 | | - path | 同上上传对象参数一致 | String | 是 | | - file | 同上上传对象参数一致 | File、Blob、String、ArrayBuffer | 是 | | - pdFileHash | 同上上传对象参数一致 | Boolean | 否 | | params | 同上上传对象参数一致 | Object | 否 |

响应参数

{
  "files": [
    {
      "options": {
        "Index": "0",
        "TaskId": "66dc56d8-fbd7-15ca-3611-f541f1c214b2",
        "Bucket": "instance-xxxx",
        "Region": "ap-guangzhou",
        "Key": "a1/test/test.edf95.txt",
        "SliceSize": 5242880
      },
      "error": null,
      "data": {
        "statusCode": 200,
        "headers": {
          "content-length": "0",
          "etag": "\"2a97bec793b2838b6ef8a0652e3fabf4\"",
          "x-cos-request-id": "NjIxODhlNGNfNzMwMmMwYl8yMzNlZF9iYWYxMTUz"
        },
        "Location": "instance-xxxx.cos.ap-guangzhou.myqcloud.com/a1/test/test.edf95.txt",
        "ETag": "\"2a97bec793b2838b6ef8a0652e3fabf4\""
      }
    },
    {
      "options": {
        "Index": "1",
        "TaskId": "cbebb248-8903-9fde-aecf-992423e4edf2",
        "Bucket": "instance-xxxx",
        "Region": "ap-guangzhou",
        "Key": "a1/test/tes1.txt",
        "SliceSize": 5242880
      },
      "error": null,
      "data": {
        "statusCode": 200,
        "headers": {
          "content-length": "0",
          "etag": "\"2a97bec793b2838b6ef8a0652e3fabf4\"",
          "x-cos-request-id": "NjIxODhlNGNfZWIxNDZiMGJfN2FhY19hYmQ2YWQ1"
        },
        "Location": "instance-xxxx.cos.ap-guangzhou.myqcloud.com/a1/test/tes1.txt",
        "ETag": "\"2a97bec793b2838b6ef8a0652e3fabf4\""
      }
    },
    {
      "options": {
        "Index": "2",
        "TaskId": "a57a5591-7233-3d3f-2670-9285d4e8d6cf",
        "Bucket": "instance-xxxx",
        "Region": "ap-guangzhou",
        "Key": "a1/test/test2.ed095.txt",
        "SliceSize": 5242880
      },
      "error": null,
      "data": {
        "statusCode": 200,
        "headers": {
          "content-length": "0",
          "etag": "\"2a97bec793b2838b6ef8a0652e3fabf4\"",
          "x-cos-request-id": "NjIxODhlNGNfNzgxMzc2MGJfMTk0M2VfYWE0N2IzNA=="
        },
        "Location": "instance-xxxx.cos.ap-guangzhou.myqcloud.com/a1/test/test2.ed095.txt",
        "ETag": "\"2a97bec793b2838b6ef8a0652e3fabf4\""
      }
    }
  ]
}

读取对象内容

方法:pagodaCos.getObjectUrl(path, params);

请求参数

| 属性名 | 参数描述 | 类型 | 是否必填 | | --- | --- | --- | --- | | path | 要下载的的文件子路径 | string | 是 | | params | ... | Object | 否 | | - pdVerify | 如果 path 传值为带域名的链接,会验证是否符合配置域名 | boolean | 否 | | - ...其它 | 其它参数,前往 腾讯 COS - 对象访问 URL ,查看参数说明 | any | 否 |

// 支持3种path传值
const { Url } = await pagodaCos.getObjectUrl('test/test.txt'); // 兼容`1.0.8`以前的版本

const { Url } = await pagodaCos.getObjectUrl({
  Key: '${prefix}/test/test.txt',
});
const { Url } = await pagodaCos.getObjectUrl(
  'https?://{host}/${prefix}/test/test.txt'
);
  1. COS 生成的Locationhttps?://${Bucket}.cos.${Region}.myqcloud.com/${Key}

Note: 生成预签名链接 ,请查看链接

响应参数

{
  "Url": "http://instance-xxxx.cos.ap-guangzhou.myqcloud.com/a1/test/test.txt?q-sign-algorithm=sha1&q-ak=AKIDJxTmcTjw3a-HNNj8_BsIjO2JmowK4JBik0QRwCG0HjmAkzuFkIYGcwGJAVWf_d2x&q-sign-time=1645778968;1645780768&q-key-time=1645778968;1645780768&q-header-list=host&q-url-param-list=&q-signature=c3f0ccdf6d678555236be8d5a2d616126bf1485e&x-cos-security-token=2BQX5UTmbr290Q5AlL2suCT25rIuZoIa8b08c3fb51d1ac9660c53c3d04f2b415zUOAXO6K7fHi8SmXqzEOIYhtH8-KLkmITS7M8hWBVkPFGlF43vfbnrZO-OeJCYiIPycs_ZQuescVgejpOsMMSBcig6LTc58GgxMHj3-H9PfcQF2pG0A5TNRKLreqWuctXeBbddp677P8_qeuE6297rgV--W6JiWUgOoqt7CquxQwojlBhOyD_OIrgzXF3Ww0F3jACeEFnwEM4RXgR7ChQc5HmV4FQ_qcx25APN6ofOsLz91Eg1qxrND3WCZoxF_My8VOM-_EEm9XozEkn3TXXVO3YqRrilXb5A26cJHyKYw"
}

解析 COSLocation方法:urlParse

方法:pagodaCos.urlParse(url);

请求参数

| 属性名 | 参数描述 | 类型 | 是否必填 | | ------ | ---------------------------------------- | ------ | -------- | | url | 要解析的链接,如:https?://${Location} | string | 是 |

响应参数
// instance-xxxxx.cos.ap-guangzhou.myqcloud.com:8000/a1/test/picture.png
// ==>
{
  host: 'instance-xxxxx.cos.ap-guangzhou.myqcloud.com',
  key: 'a1/test/picture.png',
  prefix: 'a1',
  bucket: 'instance-xxxxx',
  region: 'ap-guangzhou',
  protocol: 'https',
  parseData: {
    preventInvalidHostname: false,
    query: '',
    protocol: 'https',
    username: null,
    password: null,
    hostname: 'instance-xxxxx.cos.ap-guangzhou.myqcloud.com',
    port: '',
    path: '/a1/test/picture.png',
  },
}

url 为*.myqcloud.com域名时,可不要携带protocol

获取配置 API

  1. pagodaCos.getConfig()

响应参数

{
  "region": "ap-guangzhou",
  "bucket": "instance-xxxx",
  "prefix": "a1"
}
  1. pagodaCos.getUploadFileConfig({path, file, params, type})

请求参数

| 属性名 | 参数描述 | 类型 | 是否必填 | | --- | --- | --- | --- | | type | 返回参数类型 | 'putObject'、'sliceUploadFile'、'uploadFile'、'uploadFiles'、'config' | 否 | | path | 文件路径 | String | 否 | | file | 文件 | File、Blob、String、ArrayBuffer | 否 | | params | 同上上传对象参数一致 | Object | 否 | | - pdFileHash | 同上上传对象参数一致 | Boolean | 否 | | - ...其它 | 需要合并的参数 | any | 否 |

返回参数

{
  "Bucket": "instance-xxxx",
  "Region": "ap-guangzhou",
  "Prefix": "a1",
  "StorageClass": "STANDARD",
  "Body": "File {}"
  // ...
}

腾讯 COS 其它 API 调用示例

const { Bucket, Region, Prefix } = await pagodaCos.getUploadFileConfig({
  type: 'config',
});

const result = await pagodaCos.cos.getBucket({
  Bucket,
  Region,
  Prefix: `${Prefix}/test`,
});