Giter Site home page Giter Site logo

alibabacloud-typescript-sdk's People

Contributors

peze avatar sdk-team avatar wenzuochao avatar yndu13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

alibabacloud-typescript-sdk's Issues

oss ListObjects 服务器响应的是 xml,gateway-oss 在只有一个对象时 parseXml 解析结果的不是数组,会报错 type of contents is mismatch, expect array, but object

node_modules/@alicloud/gateway-oss/src/client.ts:207 (gateway-oss 这个仓库还没有上传 GitHub)

    let result : {[key: string ]: any} = XML.parseXml(bodyStr, null);

因为 ListObjects 返回结果里只有一个 标签,这行 parseXml 解析的结果 contents 就是一个 Content Object 而不是 Array

然后在
https://github.com/aliyun/tea-typescript/blob/1.x/src/tea.ts#L329

        } else if (type.type === 'array') {
            if (!Array.isArray(value)) {
                throw new Error(`type of ${key} is mismatch, expect array, but ${typeof value}`);
            }

contents 的 type.type 是 'array',但是 parseXml 因为只有一个 标签,本来应该是 array 但是解析成 object 了,这行旧 throw Error 了
Uncaught Error: type of contents is mismatch, expect array, but object

太坑了,没有 `.toMap()` 永远小写参数传过去

body: Util.toMap(request),

传进入 { "videoId": "xxx" } 出来还是原样的,无限重复这个错误

Error: MissingVideoId: code: 400, VideoId is mandatory for this action. request id: 22CBADE2-0C99-5366-A371-0E385C4DB981

明明你个** requestGetPlayInfoRequest类型,可以 toMap(),真的日了狗了。。。

async getPlayInfoWithOptions(request: GetPlayInfoRequest, runtime: $Util.RuntimeOptions): Promise<GetPlayInfoResponse> {
  // ...
  let req = new $OpenApi.OpenApiRequest({
    body: request.toMap(),
  });
  // ...
}

TS版SDK完全无法使用,可以补一下文档吗

对比下之前项目的接口截图,使用的时候,就直接写入地址,参数从接口文档里粘贴下来就行了,现在TS这个版本,弄的极其复杂庞大,真的是学习了Java所有的臃肿难用的传统,确没有沾到一点点js便捷好用的边啊。琢磨及时分钟了,头大死了,而且官方的Api Explorer的Nodejs版本代码示例也没有。

你们这样乱七八糟命名,鬼知道什么接口用什么方法啊,我想试个gettoken,全文检索都找不到,叫我如何用啊。
哪怕对比下面java的代码,也是极其简单啊,能不能不要让java程序员来坑我们nodejs程序员呢,谢谢了,我又只能换回以前的SDK改改用了...

DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest req = new OapiGettokenRequest();
req.setHttpMethod("GET");
OapiGettokenResponse rsp = client.execute(req);
System.out.println(rsp.getBody());

image

@alicloud/bailian20230601 包在next.js14的框架中,进行流式数据请求之前获取token的时候会进行报错

这是用于测试的路由文件代码

// 文件路径 app/api/test-stream/route.ts

import aliTokenHandler from "@/utils/aliTokenHandler";
import {NextRequest, NextResponse} from 'next/server';

export const runtime = 'edge';

async function handler(request: NextRequest, res: NextResponse, token: string) {

  const responseStream = new TransformStream();
  const writer = responseStream.writable.getWriter();
  const encoder = new TextEncoder();

  try {
    const responseChunks = `This is a response from a NextJS server. Thank you for your message! ${token}`.split(' ');
    sendStream(writer, encoder, responseChunks);
  } catch (err) {
    console.log(JSON.stringify(err));
    throw err;
  }

  return new Response(responseStream.readable, {
    headers: {
      'Content-Type': 'text/event-stream',
      Connection: 'keep-alive',
      'Cache-Control': 'no-cache, no-transform',
    },
  });

  function sendStream(
    writer: WritableStreamDefaultWriter<any>,
    encoder: TextEncoder,
    responseChunks: string[],
    chunkIndex = 0
  ) {
    setTimeout(() => {
      const chunk = responseChunks[chunkIndex];
      if (chunk) {
        // Sends response back to Deep Chat using the Response format:
        // https://deepchat.dev/docs/connect/#Response
        writer.write(encoder.encode(`data: ${JSON.stringify({text: `${chunk} `})}\n\n`));
        sendStream(writer, encoder, responseChunks, chunkIndex + 1);
      } else {
        writer.close();
      }
    }, 70);
  }
}

const GET = aliTokenHandler(handler)

export {
  GET
}

这是aliTokenHandler封装的方法

// 文件路径 /utils/aliTokenHandler
import {NextRequest, NextResponse} from 'next/server';
import Client from '@alicloud/bailian20230601'
import * as memoryCache from 'memory-cache'

type CallbackFunc = (req: NextRequest, res: NextResponse, token: string) => Promise<NextResponse<Response>> | Promise<Response>;

async function getToken() {

  const cacheKey = 'bailian_token'

  if (memoryCache.get(cacheKey)) {
    return memoryCache.get(cacheKey)
  }

  const accessKeyId = process.env.ALY_ACCESS_KEY_ID || '';
  const accessKeySecret = process.env.ALY_ACCESS_KEY_SECRET || '';
  const agentKey = process.env.ALY_BAILIAN_AGENT_KEY || '';
  const endpoint = 'bailian.cn-beijing.aliyuncs.com'

  // @ts-ignore
  const c = new Client({
    accessKeyId: accessKeyId,
    accessKeySecret: accessKeySecret,
    endpoint: endpoint
  })

  async function createToken() {
    const response = await c.createToken(
      // @ts-ignore
      { agentKey: agentKey }
    );

    const responseBody = response.body
    if (responseBody === null) {
      throw new Error('failed to create token')
    }

    if (responseBody.success !== true) {
      let requestId = responseBody.requestId;
      if (requestId == null) {
        requestId = response.headers["x-acs-request-id"];
      }

      let error = "failed to create token " + responseBody.message + ", requestId: " + requestId;
      throw new Error(error)
    }

    const tokenData = responseBody.data
    if (!tokenData) {
      throw new Error("failed to create token");
    }
    return tokenData
  }

  try {
    const { token = '', expiredTime = 0} = await createToken()
    memoryCache.put(cacheKey, token, expiredTime * 1000 - new Date().getTime());
    console.log('token: ' + memoryCache.get(cacheKey) + ', expiredTime: ' + expiredTime);
    return token
  } catch (err) {
    console.error('failed to create token, err: ', err);
    throw err
  }
}

export default function errorHandler(callbackFunc: CallbackFunc) {
  return async (req: NextRequest, res: NextResponse) => {
    try {
      const token = await getToken()
      return await callbackFunc(req, res, token);
    } catch (error) {
      console.error('API Error:', error);
      // Sends response back to Deep Chat using the Response format:
      // https://deepchat.dev/docs/connect/#Response
      return NextResponse.json({error}, {status: 500});
    }
  };
}

执行步骤

在浏览器访问 http://localhost:3000/api/test-stream

预期结果

流式输出文本并且返回token

实际结果

报错,以下是控制台错误日志

 ○ Compiling /api/test-stream ...
 ⨯ ./node_modules/@alicloud/credentials/dist/src/oidc_role_arn_credential.js:9:29
Module not found: Can't resolve 'fs'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/@alicloud/credentials/dist/src/client.js
./node_modules/@alicloud/openapi-client/dist/client.js
./node_modules/@alicloud/bailian20230601/dist/client.js
./src/utils/aliTokenHandler.ts
./src/app/api/test-stream/route.ts
./node_modules/next/dist/build/webpack/loaders/next-edge-app-route-loader/index.js?absolutePagePath=%2FUsers%2Fhuangxiaotong%2Fwork%2Fpenglai%2Fsrc%2Fapp%2Fapi%2Ftest-stream%2Froute.ts&page=%2Fapi%2Ftest-stream%2Froute&appDirLoader=bmV4dC1hcHAtbG9hZGVyP25hbWU9YXBwJTJGYXBpJTJGdGVzdC1zdHJlYW0lMkZyb3V0ZSZwYWdlPSUyRmFwaSUyRnRlc3Qtc3RyZWFtJTJGcm91dGUmYXBwUGF0aHM9JnBhZ2VQYXRoPXByaXZhdGUtbmV4dC1hcHAtZGlyJTJGYXBpJTJGdGVzdC1zdHJlYW0lMkZyb3V0ZS50cyZhcHBEaXI9JTJGVXNlcnMlMkZodWFuZ3hpYW90b25nJTJGd29yayUyRnBlbmdsYWklMkZzcmMlMkZhcHAmcGFnZUV4dGVuc2lvbnM9dHN4JnBhZ2VFeHRlbnNpb25zPXRzJnBhZ2VFeHRlbnNpb25zPWpzeCZwYWdlRXh0ZW5zaW9ucz1qcyZyb290RGlyPSUyRlVzZXJzJTJGaHVhbmd4aWFvdG9uZyUyRndvcmslMkZwZW5nbGFpJmlzRGV2PXRydWUmdHNjb25maWdQYXRoPXRzY29uZmlnLmpzb24mYmFzZVBhdGg9JmFzc2V0UHJlZml4PSZuZXh0Q29uZmlnT3V0cHV0PSZwcmVmZXJyZWRSZWdpb249Jm1pZGRsZXdhcmVDb25maWc9ZTMwJTNEIQ%3D%3D&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!
 ⚠ ./node_modules/sax/lib/sax.js
Module not found: Can't resolve 'stream' in '/Users/huangxiaotong/work/penglai/node_modules/sax/lib'

Import trace for requested module:
./node_modules/sax/lib/sax.js
./node_modules/xml2js/lib/parser.js
./node_modules/xml2js/lib/xml2js.js
./node_modules/@alicloud/tea-xml/dist/client.js
./node_modules/@alicloud/openapi-client/dist/client.js
./node_modules/@alicloud/bailian20230601/dist/client.js
./src/utils/aliTokenHandler.ts
./src/app/api/test-stream/route.ts
./node_modules/next/dist/build/webpack/loaders/next-app-loader.js?name=app%2Fapi%2Ftest-stream%2Froute&page=%2Fapi%2Ftest-stream%2Froute&appPaths=&pagePath=private-next-app-dir%2Fapi%2Ftest-stream%2Froute.ts&appDir=%2FUsers%2Fhuangxiaotong%2Fwork%2Fpenglai%2Fsrc%2Fapp&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&rootDir=%2FUsers%2Fhuangxiaotong%2Fwork%2Fpenglai&isDev=true&tsconfigPath=tsconfig.json&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!./src/app/api/test-stream/route.ts?__next_edge_ssr_entry__
 ⚠ Fast Refresh had to perform a full reload due to a runtime error.

当我不使用流式返回的时候这个API工作是正常的

return NextResponse.json({text: `This is a respone from a NextJS edge server. Thankyou for your message! ${token}`});

我现在需要接入通义千问大模型的流式传输的接口,无法以这种形式去创建token

调用SDK报错:nodejs.TypeError: Cannot read properties of undefined (reading 'getAccessKeyId')

我的代码:
import { Service } from 'egg'
import Sls20201230, * as $Sls20201230 from '@alicloud/sls20201230';
import * as $OpenApi from '@alicloud/openapi-client';
const sls = new Sls20201230(
new $OpenApi.Config({
accessKeyId: "",
secretAccessKey: "
",
endpoint: '***',
})
)
const req = new $Sls20201230.GetLogsV2Request()
req.from = from
req.to = to
req.query = appId: ${appId}
const { body } = await sls.getLogs("teambition", "open-api-gateway", req)
报错内容:
00:00:00&endTime=2023-11-02%2000:00:00&requestId] nodejs.TypeError: Cannot read properties of undefined (reading 'getAccessKeyId')
at Client.modifyRequest (/Users/jinyihao/Desktop/dev-center/node_modules/@[email protected]@@alicloud/gateway-sls/src/client.ts:36:40)
at Client.execute (/Users/jinyihao/Desktop/dev-center/node_modules/
@[email protected]@@alicloud/openapi-client/src/client.ts:1202:25)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Client.getLogsWithOptions (/Users/jinyihao/Desktop/dev-center/node_modules/@[email protected]@@alicloud/sls20201230/src/client.ts:9900:39)
at Client.getLogs (/Users/jinyihao/Desktop/dev-center/node_modules/
@[email protected]@@alicloud/sls20201230/src/client.ts:9906:12)
at SlsService.queryLog (/Users/jinyihao/Desktop/dev-center/app/service/app_log.ts:23:26)

proxy 无效

proxy无效; 在代码中没看到runtime中proxy相关配置被使用?

这sdk让人很失望...

oss PutObject 需要使用 commonHeaders 中的 Content-Type 作为参数,但是 gateway-oss 会强行设为 application/octet-stream

https://help.aliyun.com/zh/oss/developer-reference/putobject

node_modules/@alicloud/gateway-oss/src/client.ts:130

    if (!Util.isUnset(request.body)) {
      if (String.equals(request.reqBodyType, "xml")) {
        let reqBodyMap = Util.assertAsMap(request.body);
        request.stream = new $tea.BytesReadable(XML.toXML(reqBodyMap));
        request.headers["content-type"] = "application/xml";
      } else if (String.equals(request.reqBodyType, "json")) {
        let reqBodyStr = Util.toJSONString(request.body);
        request.stream = new $tea.BytesReadable(reqBodyStr);
        request.headers["content-type"] = "application/json; charset=utf-8";
      } else if (String.equals(request.reqBodyType, "formData")) {
        let reqBodyForm = Util.assertAsMap(request.body);
        request.stream = new $tea.BytesReadable(OpenApiUtil.toForm(reqBodyForm));
        request.headers["content-type"] = "application/x-www-form-urlencoded";
      } else if (String.equals(request.reqBodyType, "binary")) {
        attributeMap.key = {
          crc: "",
          md5: "",
        };
        request.stream = OSSUtil.inject(request.stream, attributeMap.key);
        request.headers["content-type"] = "application/octet-stream";
      }

    }

编译cjs, esm 产物

现在ts里相当于是esm代码, 编译产物是cjs格式,

这样就造成在devbuildimport default不一致

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.