New Client-Function getLinkedRecords Question

Hi, I come back to this topic which was closed automatically:

I try to implement the function, but I get only errors:

        const erg:any = await base.getLinkedRecords(tableId, column_key, [{
			'row_id': row_id, 'limit': 1000, 'offset': 0}]);

I looked into the code changes you made and I don’t understand it completely:
in the newly introduced function base.getLinkedRecords you return the result by creating a new axios object. This is the only situation where you do this for an endpoint in the entire base.js file:


		const req = axios.create({
			baseURL: this.dtableDB,
			headers: { Authorization: 'Token ' + this.accessToken }
		});
		return req.post(url, { ...data }).then((response) => {
			return Promise.resolve((response && response.data) || {});
		});

By this I get an error of “ECONNREFUSED”:

method: 'post',
url: 'api/v1/linked-records/a3af4841-021c-4972-922b-123123123/',
data: '{"link_column":"asdf","table_id":"7O8o","rows":[{"row_id":"fTkDL7_CQf2G5k_hhxNLFw","limit":1000,"offset":0}]}'

I changed it now to the approach you use for the other endpoints:

		return this.req.post(url, { ...data }).then((response) => {
			return Promise.resolve((response && response.data) || {});
		});

By doing so, it reaches your server, but I get an 404 Error:

code: ‘ERR_BAD_REQUEST’,
responseUrl: ‘https://cloud.seatable.io/dtable-server/api/v1/linked-records/a3af4841-021c-4972-922b-123123123123/’,

Do I do something wrong or is it a general problem?

Here is a script I use, which can work with my base in https://cloud.seatable.io . It need to be run with node.js.

const { Base } = require('seatable-api');

const config = {
  server: 'https://cloud.seatable.io',
  APIToken: '',
};

const getLinkedRecords = async () => {
  const base = new Base(config);
  await base.auth();

  const metadata = await base.getMetadata();
  const tables = metadata.tables;
  const tableName = 'Table2';
  const linkColumnName = 'link-table1';
  const table = tables.find((table) => table.name === tableName);
  const linkColumn = table.columns.find(column => column.name === linkColumnName);
  const queryingRows = [
    { row_id: 'IYwwttG_RGKBub7zC9ftsw', 'limit': 1000, 'offset': 0 },
  ];
  const linkedRecords = await base.getLinkedRecords(table._id, linkColumn.key, queryingRows);
  console.log(linkedRecords);
};

getLinkedRecords();

The URL should be ‘https://cloud.seatable.io/dtable-db/api/v1/linked-records/a3af4841-021c-4972-922b-123123123123/

dtable-server → dtable-db

Currently some APIs use the dtable-server component, some APIs use the dtable-db component.

thank you for your answers!

I tried your code and altered it slightly to my approach (I use typescript)

export async function getLinkedRecords(tableName: string, columnName: string, row_id:string) {
	console.log(`getLinkedRecords ${tableName} ${columnName} ${row_id}`)

	const config = {
		server: process.env.seatebleUrl,
		APIToken: process.env.seatableApiToken
	  };
	  
	  const getLinkedRecords = async () => {
		const base = new Base(config);
		await base.auth();
	  
		const metadata = await base.getMetadata();
		const tables: Table[] = (metadata as any).tables!;

		const table = tables.find((table) => table.name === tableName);
		const linkColumn = table?.columns.find(column => column.name === columnName);
		const queryingRows = [
		  { row_id: row_id, 'limit': 1000, 'offset': 0 },
		];

		console.log('⚠️⚠️⚠️',table?._id, linkColumn.key,queryingRows )

		const linkedRecords = await base.getLinkedRecords(table?._id, linkColumn.key, queryingRows);
		console.log(linkedRecords);
	  };
	  console.log(await getLinkedRecords())
}

But I still get this error:

Summary
AxiosError: connect ECONNREFUSED ::1:80
    at AxiosError.from (file:///Users/larslehmann/Projects/GithubDesktop/MECFS/MRR/node_modules/axios/lib/core/AxiosError.js:89:14)
    at RedirectableRequest.handleRequestError (file:///Users/larslehmann/Projects/GithubDesktop/MECFS/MRR/node_modules/axios/lib/adapters/http.js:591:25)
    at RedirectableRequest.emit (node:events:513:28)
    at eventHandlers.<computed> (/Users/larslehmann/Projects/GithubDesktop/MECFS/MRR/node_modules/follow-redirects/index.js:14:24)
    at ClientRequest.emit (node:events:513:28)
    at Socket.socketErrorListener (node:_http_client:502:9)
    at Socket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  port: 80,
  address: '::1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -61,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: {
      FormData: [Function: FormData] {
        LINE_BREAK: '\r\n',
        DEFAULT_CONTENT_TYPE: 'application/octet-stream'
      },
      Blob: [class Blob]
    },
    validateStatus: [Function: validateStatus],
    headers: AxiosHeaders {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      Authorization: 'Token THETOKEN',
      'User-Agent': 'axios/1.4.0',
      'Content-Length': '109',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    method: 'post',
    url: 'api/v1/linked-records/a3af4841-021c-4972-922b-13213123132/',
    data: '{"link_column":"rZnk","table_id":"7O8o","rows":[{"row_id":"fTkDL7_CQf2G5k_hhxNLFw","limit":1000,"offset":0}]}'
  },
  request: <ref *2> Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError],
      socket: [Function: handleRequestSocket]
    },
    _eventsCount: 3,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: Infinity,
      protocol: 'http:',
      path: '/api/v1/linked-records/a3af4841-021c-4972-922b-12313123123/',
      method: 'POST',
      headers: [Object: null prototype] {
        Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/json',
        Authorization: 'Token THETOKEN',
        'User-Agent': 'axios/1.4.0',
        'Content-Length': '109',
        'Accept-Encoding': 'gzip, compress, deflate, br'
      },
      agents: { http: undefined, https: undefined },
      auth: undefined,
      family: undefined,
      lookup: undefined,
      beforeRedirect: [Function: dispatchBeforeRedirect],
      beforeRedirects: { proxy: [Function: beforeRedirect] },
      hostname: 'localhost',
      port: '',
      agent: undefined,
      nativeProtocols: {
        'http:': {
          _connectionListener: [Function: connectionListener],
          METHODS: [
            'ACL',         'BIND',       'CHECKOUT',
            'CONNECT',     'COPY',       'DELETE',
            'GET',         'HEAD',       'LINK',
            'LOCK',        'M-SEARCH',   'MERGE',
            'MKACTIVITY',  'MKCALENDAR', 'MKCOL',
            'MOVE',        'NOTIFY',     'OPTIONS',
            'PATCH',       'POST',       'PROPFIND',
            'PROPPATCH',   'PURGE',      'PUT',
            'REBIND',      'REPORT',     'SEARCH',
            'SOURCE',      'SUBSCRIBE',  'TRACE',
            'UNBIND',      'UNLINK',     'UNLOCK',
            'UNSUBSCRIBE'
          ],
          STATUS_CODES: {
            '100': 'Continue',
            '101': 'Switching Protocols',
            '102': 'Processing',
            '103': 'Early Hints',
            '200': 'OK',
            '201': 'Created',
            '202': 'Accepted',
            '203': 'Non-Authoritative Information',
            '204': 'No Content',
            '205': 'Reset Content',
            '206': 'Partial Content',
            '207': 'Multi-Status',
            '208': 'Already Reported',
            '226': 'IM Used',
            '300': 'Multiple Choices',
            '301': 'Moved Permanently',
            '302': 'Found',
            '303': 'See Other',
            '304': 'Not Modified',
            '305': 'Use Proxy',
            '307': 'Temporary Redirect',
            '308': 'Permanent Redirect',
            '400': 'Bad Request',
            '401': 'Unauthorized',
            '402': 'Payment Required',
            '403': 'Forbidden',
            '404': 'Not Found',
            '405': 'Method Not Allowed',
            '406': 'Not Acceptable',
            '407': 'Proxy Authentication Required',
            '408': 'Request Timeout',
            '409': 'Conflict',
            '410': 'Gone',
            '411': 'Length Required',
            '412': 'Precondition Failed',
            '413': 'Payload Too Large',
            '414': 'URI Too Long',
            '415': 'Unsupported Media Type',
            '416': 'Range Not Satisfiable',
            '417': 'Expectation Failed',
            '418': "I'm a Teapot",
            '421': 'Misdirected Request',
            '422': 'Unprocessable Entity',
            '423': 'Locked',
            '424': 'Failed Dependency',
            '425': 'Too Early',
            '426': 'Upgrade Required',
            '428': 'Precondition Required',
            '429': 'Too Many Requests',
            '431': 'Request Header Fields Too Large',
            '451': 'Unavailable For Legal Reasons',
            '500': 'Internal Server Error',
            '501': 'Not Implemented',
            '502': 'Bad Gateway',
            '503': 'Service Unavailable',
            '504': 'Gateway Timeout',
            '505': 'HTTP Version Not Supported',
            '506': 'Variant Also Negotiates',
            '507': 'Insufficient Storage',
            '508': 'Loop Detected',
            '509': 'Bandwidth Limit Exceeded',
            '510': 'Not Extended',
            '511': 'Network Authentication Required'
          },
          Agent: [Function: Agent] { defaultMaxSockets: Infinity },
          ClientRequest: [Function: ClientRequest],
          IncomingMessage: [Function: IncomingMessage],
          OutgoingMessage: [Function: OutgoingMessage],
          Server: [Function: Server],
          ServerResponse: [Function: ServerResponse],
          createServer: [Function: createServer],
          validateHeaderName: [Function: __node_internal_],
          validateHeaderValue: [Function: __node_internal_],
          get: [Function: get],
          request: [Function: request],
          setMaxIdleHTTPParsers: [Function: setMaxIdleHTTPParsers],
          maxHeaderSize: [Getter],
          globalAgent: [Getter/Setter]
        },
        'https:': {
          Agent: [Function: Agent],
          globalAgent: Agent {
            _events: [Object: null prototype],
            _eventsCount: 2,
            _maxListeners: undefined,
            defaultPort: 443,
            protocol: 'https:',
            options: [Object: null prototype],
            requests: [Object: null prototype] {},
            sockets: [Object: null prototype] {},
            freeSockets: [Object: null prototype] {},
            keepAliveMsecs: 1000,
            keepAlive: false,
            maxSockets: Infinity,
            maxFreeSockets: 256,
            scheduling: 'lifo',
            maxTotalSockets: Infinity,
            totalSocketCount: 0,
            maxCachedSessions: 100,
            _sessionCache: [Object],
            [Symbol(kCapture)]: false
          },
          Server: [Function: Server],
          createServer: [Function: createServer],
          get: [Function: get],
          request: [Function: request]
        }
      },
      pathname: '/api/v1/linked-records/a3af4841-021c-4972-922b-0d6049e307ea/'
    },
    _ended: false,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 109,
    _requestBodyBuffers: [
      {
        data: Buffer(109) [Uint8Array] [
          123,  34, 108, 105, 110, 107,  95,  99, 111, 108, 117, 109,
          110,  34,  58,  34, 114,  90, 110, 107,  34,  44,  34, 116,
           97,  98, 108, 101,  95, 105, 100,  34,  58,  34,  55,  79,
           56, 111,  34,  44,  34, 114, 111, 119, 115,  34,  58,  91,
          123,  34, 114, 111, 119,  95, 105, 100,  34,  58,  34, 102,
           84, 107,  68,  76,  55,  95,  67,  81, 102,  50,  71,  53,
          107,  95, 104, 104, 120,  78,  76,  70, 119,  34,  44,  34,
          108, 105, 109, 105, 116,  34,  58,  49,  48,  48,  48,  44,
           34, 111, 102, 102,
          ... 9 more items
        ],
        encoding: undefined
      }
    ],
    _onNativeResponse: [Function (anonymous)],
    _currentRequest: <ref *1> ClientRequest {
      _events: [Object: null prototype] {
        response: [Function: bound onceWrapper] {
          listener: [Function (anonymous)]
        },
        abort: [Function (anonymous)],
        aborted: [Function (anonymous)],
        connect: [Function (anonymous)],
        error: [Function (anonymous)],
        socket: [Function (anonymous)],
        timeout: [Function (anonymous)]
      },
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: '109',
      _hasBody: true,
      _trailer: '',
      finished: false,
      _headerSent: true,
      _closed: false,
      socket: Socket {
        connecting: false,
        _hadError: true,
        _parent: null,
        _host: 'localhost',
        _closeAfterHandlingError: false,
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 16384,
          buffer: BufferList { head: null, tail: null, length: 0 },
          length: 0,
          pipes: [],
          flowing: true,
          ended: false,
          endEmitted: false,
          reading: true,
          constructed: true,
          sync: false,
          needReadable: true,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          errorEmitted: true,
          emitClose: false,
          autoDestroy: true,
          destroyed: true,
          errored: Error: connect ECONNREFUSED ::1:80
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
            errno: -61,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '::1',
            port: 80
          },
          closed: true,
          closeEmitted: true,
          defaultEncoding: 'utf8',
          awaitDrainWriters: null,
          multiAwaitDrain: false,
          readingMore: false,
          dataEmitted: false,
          decoder: null,
          encoding: null,
          [Symbol(kPaused)]: false
        },
        _events: [Object: null prototype] {
          end: [Function: onReadableStreamEnd],
          connect: [ [Function], [Function], [Function] ],
          free: [Function: onFree],
          close: [
            [Function: onClose],
            [Function: socketCloseListener],
            [Function]
          ],
          timeout: [Function: onTimeout],
          agentRemove: [Function: onRemove],
          error: [Function: socketErrorListener],
          drain: [Function: ondrain]
        },
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: WritableState {
          objectMode: false,
          highWaterMark: 16384,
          finalCalled: false,
          needDrain: false,
          ending: false,
          ended: false,
          finished: false,
          destroyed: true,
          decodeStrings: false,
          defaultEncoding: 'utf8',
          length: 681,
          writing: true,
          corked: 0,
          sync: false,
          bufferProcessing: false,
          onwrite: [Function: bound onwrite],
          writecb: [Function (anonymous)],
          writelen: 681,
          afterWriteTickInfo: null,
          buffered: [],
          bufferedIndex: 0,
          allBuffers: true,
          allNoop: true,
          pendingcb: 1,
          constructed: true,
          prefinished: false,
          errorEmitted: true,
          emitClose: false,
          autoDestroy: true,
          errored: Error: connect ECONNREFUSED ::1:80
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
            errno: -61,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '::1',
            port: 80
          },
          closed: true,
          closeEmitted: true,
          [Symbol(kOnFinished)]: []
        },
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: [
          {
            chunk: 'POST /api/v1/linked-records/a3af4841-021c-4972-922b-123123123/ HTTP/1.1\r\n' +
              'Accept: application/json, text/plain, */*\r\n' +
              'Content-Type: application/json\r\n' +
              'Authorization: Token THETOKEN\r\n' +
              'User-Agent: axios/1.4.0\r\n' +
              'Content-Length: 109\r\n' +
              'Accept-Encoding: gzip, compress, deflate, br\r\n' +
              'Host: localhost\r\n' +
              'Connection: close\r\n' +
              '\r\n',
            encoding: 'latin1',
            callback: [Function: nop]
          },
          {
            chunk: [Buffer [Uint8Array]],
            encoding: 'buffer',
            callback: [Function (anonymous)]
          },
          allBuffers: false
        ],
        _pendingEncoding: '',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular *1],
        [Symbol(async_id_symbol)]: 6136,
        [Symbol(kHandle)]: null,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBuffer)]: null,
        [Symbol(kBufferCb)]: null,
        [Symbol(kBufferGen)]: null,
        [Symbol(kCapture)]: false,
        [Symbol(kSetNoDelay)]: true,
        [Symbol(kSetKeepAlive)]: true,
        [Symbol(kSetKeepAliveInitialDelay)]: 60,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0
      },
      _header: 'POST /api/v1/linked-records/a3af4841-021c-4972-922b-123123123/ HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json\r\n' +
        'Authorization: Token THETOKEN\r\n' +
        'User-Agent: axios/1.4.0\r\n' +
        'Content-Length: 109\r\n' +
        'Accept-Encoding: gzip, compress, deflate, br\r\n' +
        'Host: localhost\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: Agent {
        _events: [Object: null prototype] {
          free: [Function (anonymous)],
          newListener: [Function: maybeEnableKeylog]
        },
        _eventsCount: 2,
        _maxListeners: undefined,
        defaultPort: 80,
        protocol: 'http:',
        options: [Object: null prototype] { noDelay: true, path: null },
        requests: [Object: null prototype] {},
        sockets: [Object: null prototype] { 'localhost:80:': [ [Socket] ] },
        freeSockets: [Object: null prototype] {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        scheduling: 'lifo',
        maxTotalSockets: Infinity,
        totalSocketCount: 1,
        [Symbol(kCapture)]: false
      },
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      joinDuplicateHeaders: undefined,
      path: '/api/v1/linked-records/a3af4841-021c-4972-922b-123123123/',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'localhost',
      protocol: 'http:',
      _redirectable: [Circular *2],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kEndCalled)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype] {
        accept: [ 'Accept', 'application/json, text/plain, */*' ],
        'content-type': [ 'Content-Type', 'application/json' ],
        authorization: [
          'Authorization',
          'Token THETOKEN'
        ],
        'user-agent': [ 'User-Agent', 'axios/1.4.0' ],
        'content-length': [ 'Content-Length', '109' ],
        'accept-encoding': [ 'Accept-Encoding', 'gzip, compress, deflate, br' ],
        host: [ 'Host', 'localhost' ]
      },
      [Symbol(errored)]: null,
      [Symbol(kUniqueHeaders)]: null
    },
    _currentUrl: 'http://localhost/api/v1/linked-records/a3af4841-021c-4972-922b-0d6049e307ea/',
    [Symbol(kCapture)]: false
  },
  cause: Error: connect ECONNREFUSED ::1:80
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
    errno: -61,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 80
  }
}

Where do I set this? As far as I see, does the Client set the URL it self.

From the error log, you connect with your local server (localhost). I suggest you try with cloud.seatable.io first.

Where do I set this? As far as I see, does the Client set the URL it self.

After calling base.auth(), the server will return the URL (or sub path) for dtable-server and dtable-db, and later API calls from the client will use the remembered URL, so you don’t need to set the URL manually.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.