The official Directus SDK for use in JavaScript!

Overview

Directus JS SDK

Installation

npm install @directus/sdk

Basic Usage

import { Directus } from '@directus/sdk';

const directus = new Directus('http://directus.example.com');

const items = await directus.items('articles').readOne(15);
console.log(items);
import { Directus } from '@directus/sdk';

const directus = new Directus('http://directus.example.com');

directus
	.items('articles')
	.readOne(15)
	.then((item) => {
		console.log(item);
	});

Reference

See the docs for a full usage reference and all supported methods.

Contributing

Requirements

  • NodeJS LTS
  • pnpm 7.5.0 or newer

Commands

The following pnpm scripts are available:

  • pnpm lint – Lint the code using Eslint / Prettier
  • pnpm test – Run the unit tests

Make sure that both commands pass locally before creating a Pull Request.

Pushing a Release

This applies to maintainers only

  1. Create a new version / tag by running pnpm version <version>. Tip: use pnpm version patch|minor|major to auto-bump the version number
  2. Push the version commit / tag to GitHub (git push && git push --tags)

The CI will automatically build and release to npm, and generate the release notes.

Comments
  • Circular dependency and preferring built-in module warnings on console

    Circular dependency and preferring built-in module warnings on console

    Preflight Checklist

    Describe the Bug

    When I run Directus on latest version it shows Circular Dependency and Preferring Built-in module alerts

    To Reproduce

    I run directus locally on my computer, in the versions mentioned below, after installing all the packages, it shows the warning

    Errors Shown

    hookSchedule:dev: preferring built-in module 'events' over local alternative at '/home/directus-cms/node_modules/events/events.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'events' over local alternative at '/home/directus-cms/node_modules/events/events.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'events' over local alternative at '/home/directus-cms/node_modules/events/events.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'url' over local alternative at '/home/directus-cms/node_modules/url/url.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'url' over local alternative at '/home/directus-cms/node_modules/url/url.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'url' over local alternative at '/home/directus-cms/node_modules/url/url.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'url' over local alternative at '/home/directus-cms/node_modules/url/url.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'url' over local alternative at '/home/directus-cms/node_modules/url/url.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'url' over local alternative at '/home/directus-cms/node_modules/url/url.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: preferring built-in module 'url' over local alternative at '/home/directus-cms/node_modules/url/url.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/index.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/cache.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/common.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/schemas.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/index.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/index.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/cache.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/common.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/schemas.js -> /home/directus-cms/node_modules/@directus/shared/node_modules/joi/lib/index.js?commonjs-proxy -> ../../node_modules/@directus/shared/node_modules/joi/lib/index.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/common.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/messages.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/template.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/common.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/common.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/messages.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/template.js -> /home/directus-cms/node_modules/@directus/shared/node_modules/joi/lib/common.js?commonjs-proxy -> ../../node_modules/@directus/shared/node_modules/joi/lib/common.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/common.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/messages.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/template.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/errors.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/annotate.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/common.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/common.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/messages.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/template.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/errors.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/common.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/template.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/errors.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/template.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/template.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/errors.js -> /home/directus-cms/node_modules/@directus/shared/node_modules/joi/lib/template.js?commonjs-proxy -> ../../node_modules/@directus/shared/node_modules/joi/lib/template.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/common.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/messages.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/template.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/ref.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/common.js
    hookSchedule:dev: Circular dependency: ../../node_modules/@directus/shared/node_modules/joi/lib/template.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/ref.js -> ../../node_modules/@directus/shared/node_modules/joi/lib/template.js
    hookSchedule:dev: Circular dependency: ../../node_modules/axios/lib/defaults.js -> ../../node_modules/axios/lib/adapters/xhr.js -> ../../node_modules/axios/lib/defaults.js
    hookSchedule:dev: Circular dependency: ../../node_modules/axios/lib/defaults.js -> ../../node_modules/axios/lib/adapters/xhr.js -> /home/directus-cms/node_modules/axios/lib/defaults.js?commonjs-proxy -> ../../node_modules/axios/lib/defaults.js
    hookSchedule:dev: Circular dependency: ../../node_modules/axios/lib/defaults.js -> ../../node_modules/axios/lib/adapters/http.js -> ../../node_modules/axios/lib/defaults.js
    hookSchedule:dev: Circular dependency: ../../node_modules/luxon/src/impl/locale.js -> ../../node_modules/luxon/src/settings.js -> ../../node_modules/luxon/src/impl/locale.js
    hookSchedule:dev: Circular dependency: ../../node_modules/luxon/src/datetime.js -> ../../node_modules/luxon/src/duration.js -> ../../node_modules/luxon/src/impl/locale.js -> ../../node_modules/luxon/src/datetime.js
    hookSchedule:dev: Circular dependency: ../../node_modules/luxon/src/datetime.js -> ../../node_modules/luxon/src/interval.js -> ../../node_modules/luxon/src/datetime.js
    hookSchedule:dev: Circular dependency: ../../node_modules/luxon/src/datetime.js -> ../../node_modules/luxon/src/info.js -> ../../node_modules/luxon/src/datetime.js
    hookSchedule:dev: Circular dependency: ../../node_modules/luxon/src/datetime.js -> ../../node_modules/luxon/src/impl/tokenParser.js -> ../../node_modules/luxon/src/datetime.js
    

    What version of Directus are you using?

    9.5.1

    What version of Node.js are you using?

    16.13.2

    What database are you using?

    Postgres 14.1

    What browser are you using?

    Chrome

    What operating system are you using?

    Ubuntu

    How are you deploying Directus?

    Docker

    Can't Reproduce Needs More Info 
    opened by LuizHAP 18
  • Directus Nuxt plugin: users.me.read -> Maximum call stack size exceeded

    Directus Nuxt plugin: users.me.read -> Maximum call stack size exceeded

    I use nuxt3 with directus and when access token expired but i refresh page i use fuction

    onst user = await $directus.users.me.read({
              fields: ['*'],
            })
    

    But in console i got this

    Token found, fetching user from server
    Exception in PromiseRejectCallback:
    @directus/sdk:819
    }
    ^
    
    RangeError: Maximum call stack size exceeded
    Exception in PromiseRejectCallback:
    @directus/sdk:923
    await this._auth.refreshIfExpired();
    ^
    
    RangeError: Maximum call stack size exceeded
    Token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU0ZmRlYmJjLTdkZTYtNGY5Ni05N2ExLWZhNTdkNzk3YzVlNCIsInJvbGUiOiI0YTE2NWVlNS0wZDgzLTRjYjQtOGYwZC1hMjBmMGNkY2RjZjciLCJhcHBfYWNjZXNzIjoxLCJhZG1pbl9hY2Nlc3MiOjEsImlhdCI6MTY2MjkxMDY5OSwiZXhwIjoxNjYyOTEwNzU5LCJpc3MiOiJkaXJlY3R1cyJ9.WjAuMNQzJS1aE5Yg-UZ3Md7VKt9r1QQDADb1OymaCSc
    TransportError: Maximum call stack size exceeded
    at Transport.request (@directus/sdk:700:19)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Transport.get (@directus/sdk:704:16)
    at async MeHandler.read (@directus/sdk:429:26)
    at async Proxy.getUser (/Users/53rg0/Sites/TEST/store/auth.ts:55:22)
    at async /Users/53rg0/Sites/TEST/plugins/directus.ts:39:85
    at async Object.callAsync (file:///Users/53rg0/Sites/TEST/node_modules/unctx/dist/index.mjs:53:16)
    at async applyPlugin (/Users/53rg0/Sites/TEST/node_modules/nuxt/dist/app/nuxt.mjs:74:23)
    at async Module.applyPlugins (/Users/53rg0/Sites/TEST/node_modules/nuxt/dist/app/nuxt.mjs:84:5)
    at async createNuxtAppServer (/Users/53rg0/Sites/TEST/node_modules/nuxt/dist/app/entry.mjs:30:7) {
      parent: TransportError: Maximum call stack size exceeded
      at Transport.request (@directus/sdk:700:19)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async Transport.post (@directus/sdk:719:16)
      at async refreshPromise (@directus/sdk:825:30)
      at async Auth.refreshIfExpired (@directus/sdk:814:13)
      at async Transport.beforeRequest (@directus/sdk:923:21)
      at async Transport.request (@directus/sdk:668:22)
      at async Transport.get (@directus/sdk:704:16)
      at async MeHandler.read (@directus/sdk:429:26)
      at async Proxy.getUser (/Users/53rg0/Sites/TEST/store/auth.ts:55:22) {
        parent: TransportError: Maximum call stack size exceeded
        at Transport.request (@directus/sdk:700:19)
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
        at async Transport.post (@directus/sdk:719:16)
        at async refreshPromise (@directus/sdk:825:30)
        at async Auth.refreshIfExpired (@directus/sdk:814:13)
        at async Transport.beforeRequest (@directus/sdk:923:21)
        at async Transport.request (@directus/sdk:668:22)
        at async Transport.post (@directus/sdk:719:16)
        at async refreshPromise (@directus/sdk:825:30)
        at async Auth.refreshIfExpired (@directus/sdk:814:13) {
          parent: [TransportError],
            response: undefined,
            errors: []
        },
        response: undefined,
          errors: []
      },
      response: undefined,
        errors: []
    }
    
    ERROR  [h3] [unhandled] Parse Error: Header overflow                                                                                                             19:14:10
    
    at Socket.socketOnData (node:_http_client:521:22)
    at Socket.emit (node:events:513:28)
    at Socket.emit (node:domain:489:12)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readable:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)
    
    

    All other functions like login etc works fine like

    const response = await $directus.auth.login({
              email,
              password,
            })
    
            // If login was successful, fetch the users data
            const user = await $directus.users.me.read({
              fields: ['*'],
            })
    

    Prombem just when token shold be refreshed, code like const refresh = await $directus.auth.refresh() returns the same

    Token found, fetching user from server
    Exception in PromiseRejectCallback:
    @directus/sdk:819
        }
        ^
    
    RangeError: Maximum call stack size exceeded
    Exception in PromiseRejectCallback:
    @directus/sdk:923
                        await this._auth.refreshIfExpired();
                                         ^
    
    
    External 
    opened by 53rg0 17
  • api token problem since 9.12

    api token problem since 9.12

    Describe the Bug

    We have 3 nodejs applications (frontend, backend, client) which access directus via js-sdk with the same static user token.

    Since 9.12 we have the problem, that after accessing the api with one application, the other application gets 401 failed requests from directus. Before 9.12 everything worked fine (we tested it, as we switched back to 9.11)

    We figured out that it is related to the internal token autoRefresh of the sdk.

    To Reproduce

    This is the log of directus, with requests from the client, after the backend has created an content object:

    08:45:29 ✨ request completed GET 401 /users/me?fields=*.* 7ms
    08:45:29 ✨ request completed GET 401 /items/page?filter=%7B%22_and%22:[%7B%22publish_date%22:%7B%22_gte%22:%222022-06-08%22%7D%7D,%7B%22publish_date%22:%7B%22_lte%22:%222022-06-29T00:00:00.000Z%22%7D%7D]%7D 4ms
    08:45:29 ✨ request completed GET 401 /items/lead?limit=6&meta=total_count&sort=-date_created 4ms
    08:45:30 ✨ request completed GET 401 /users/me?fields=*.* 4ms
    08:45:30 ✨ request completed GET 401 /items/projectConfig?fields=*.*.* 5ms
    

    this is the code we are using:

        let directus = new Directus(apiEndpoint, {
          auth: { staticToken: apiToken },
        });
    

    if we change it to this:

        let directus = new Directus(apiEndpoint, {
          auth: { staticToken: apiToken, autoRefresh: false },
        });
        await directus.auth.refresh();
    

    ...then it is possible to access the api with the client, after the backend has ceated an content object.

    But: then we are getting sometimes 403 errors in the backend :-(

    08:55:19 ✨ request completed GET 403 /items/lead?filter=%7B%22email%22:%22carsten.uepping%2Bkkkk%40contentpepper.de%22%7D&fields=*.*.* 29ms
    

    Errors Shown

    401 and 403 in the directus log, see above

    What version of Directus are you using?

    9.12.2

    What version of Node.js are you using?

    v16.14.0

    What database are you using?

    Postgres 13

    What browser are you using?

    Chrome

    How are you deploying Directus?

    running locally

    Can't Reproduce Needs More Info 
    opened by CarstenU 7
  • [Types] imprecise type for fields in readByQuery

    [Types] imprecise type for fields in readByQuery

    The current typing for fields in the following code is always resolved as string | string[] | undefined:

    declare type QueryOne<T = unknown> = {
        fields?: T extends unknown ? string | string[] : DotSeparated<T, 5> | DotSeparated<T, 5>[];
        search?: string;
        deep?: Deep<T>;
        export?: 'json' | 'csv' | 'xml';
        filter?: Filter<T>;
    };
    

    As far as I know it is because T, describing a collection item, so a record, always extends unknown.

    opened by ganlhi 6
  • Better query fields autocompletion and query return type based on fields value

    Better query fields autocompletion and query return type based on fields value

    I've implemented better autocompletion for the fields option in a query, as it now shows nested object values. The fields you pass in are also used to properly autocomplete the return value of the query.

    Further testing is not a luxury at this point, so I'd love to open the discussion and talk about your expectations regarding this.

    Please note

    These additions ~do~ probably introduce changes to how ambiguous typing is handled. ~For example: you can only pass "valid" collection names into .items() and .singleton().~

    Example

    https://user-images.githubusercontent.com/23699599/181059687-66c8e9e2-77bb-4fe8-a7ff-a80269f897ab.mp4

    The repository containing the code in the video can be found at jonahgoldwastaken/directus-sdk-types-showcase.

    Improvement 
    opened by jonahgoldwastaken 6
  • Added an AssetHandler for the Asset endpoint

    Added an AssetHandler for the Asset endpoint

    We couldn't find a way get the asset file through the sdk so we added one ourselves. We tried to follow the president set but feedback would be very welcome.

    EDIT: We also included the ability to use ResponseType within the Axios options so that streams can be used

    opened by VerantoWander 5
  • Installing 9.9.0+ requires peerDependencies (installing for node)

    Installing 9.9.0+ requires peerDependencies (installing for node)

    Describe the Bug

    When installing @directus/sdk 9.9.0+ for node it fails due to peer dependencies of @directus/shared not being able to be resolved.

    This means that I can't use those versions for my nodejs app. Of course I could install the dependencies to make it work. But don't want to install the vue peer dependency for my simple node server for example.

    Downgrading and fixing to 9.8.0 works as expected.

    I am using yarn, but don't see that being the issue.

    To Reproduce

    Upgrade a node project to the latest directus SDK version. Then try and run the project

    Errors Shown

    These are the files where the errors are shown image

    Last two Errors for example image

    What version of Directus are you using?

    9.9.1

    What version of Node.js are you using?

    12.20.0

    What database are you using?

    mariadb

    What browser are you using?

    n/a

    How are you deploying Directus?

    docker

    Optimization 
    opened by jagribble 5
  • JS-SDK: directus.auth.token is null during refresh

    JS-SDK: directus.auth.token is null during refresh

    Describe the Bug

    directus.auth.token is null while a refresh is in progress.

    The reason is the call this._storage.auth_token = null; in resetStorage().

    This is really unfortunate in case you have multiple components acting independently of each other (so no possibility to await for another component's request) and this only happens every 15min when a (auto-)refresh is needed, can be really hard to reproduce and track down.

    To Reproduce

    directus.auth.refresh(); // Important: Don't do await here console.log(directus.auth.token); // This is null

    Errors Shown

    No response

    What version of Directus are you using?

    9.11.1

    What version of Node.js are you using?

    16

    What database are you using?

    Postgres 13

    What browser are you using?

    Firefox

    How are you deploying Directus?

    Docker

    Improvement 
    opened by henk23 4
  • `XSRF-TOKEN` problems and migration to `fetch`

    `XSRF-TOKEN` problems and migration to `fetch`

    Lol, this is rather funny because I had this issue from day one of using directus sdk.

    Using the standard directus client with export const directus = new Directus('https://blu.bb'); results in CORS errors for all requests as axios seems to add a X-XSRF-TOKEN header.

    Browser console:

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blu.bb/users/me. (Reason: header ‘x-xsrf-token’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).

    Axios throws this error:

    {
      "parent": {
        "message": "Network Error",
        "name": "AxiosError",
        "stack": "",
        "config": {
          "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
          },
          "transformRequest": [
            null
          ],
          "transformResponse": [
            null
          ],
          "timeout": 0,
          "xsrfCookieName": "XSRF-TOKEN",
          "xsrfHeaderName": "X-XSRF-TOKEN",
          "maxContentLength": -1,
          "maxBodyLength": -1,
          "env": {
            "FormData": null
          },
          "headers": {
            "Accept": "application/json, text/plain, */*",
            "Authorization": "",
            "X-XSRF-TOKEN": "8e5744ca-8f3a-4a6b-9a6c-2ba8006b7423"
          },
          "baseURL": "https://blu.bb",
          "withCredentials": true,
          "method": "get",
          "url": "/users/me"
        },
        "code": "ERR_NETWORK",
        "status": null
      },
      "response": {
        "status": 0,
        "statusText": ""
      },
      "errors": []
    }
    

    I guess I can work around by setting CORS_ALLOWED_HEADERS but in my opinion this should work out of the box (or at least it should be documented somewhere).

    Regardless, as I use SvelteKit in my projects with ssr I needed to use fetch and implemented a FetchTransport which replaces the default transport. I even wrote a simple rollup plugin that gets rid of the default transport to prevent shipping axios.

    `rollup-plugin-directus.js`
    import * as walk from 'acorn-walk';
    import MagicString from 'magic-string';
    
    /** @type {import('rollup').Plugin} */
    const directus = {
      name: 'rollup-plugin-directus',
    
      resolveId: {
        handler(id, importer) {
          if (
            id === 'axios' &&
            importer &&
            importer.includes('@directus') &&
            importer.includes('sdk')
          ) {
            return {
              id: 'axios',
              external: true,
              moduleSideEffects: false,
            };
          }
        },
      },
    
      transform(code, id) {
        if (id.includes('directus') && id.includes('sdk')) {
          const ast = this.parse(code);
    
          const s = new MagicString(code, { filename: id });
    
          walk.simple(ast, {
            ClassDeclaration(node) {
              if (isClassDeclaration(node) && node.id?.name === 'Transport') {
                s.remove(node.start, node.end);
              }
            },
            ExportNamedDeclaration(node) {
              if (isExportNamedDeclaration(node)) {
                for (let idx = 0; idx < node.specifiers.length; idx++) {
                  const spec = node.specifiers[idx];
    
                  if (isExportSpecifier(spec) && spec.local.name === 'Transport') {
                    s.remove(spec.start, spec.end);
                    // Comma if not the last item.
                    if (idx < node.specifiers.length - 1) {
                      s.remove(spec.end, spec.end + 1);
                    }
                    break;
                  }
                }
              }
            },
          });
    
          return {
            code: s.toString(),
            map: s.generateMap({ source: id }),
          };
        }
      },
    };
    
    export default directus;
    
    /** @typedef {Parameters<import('acorn-walk').SimpleWalkerFn<unknown>>[0]} AcornNode */
    
    /**
     * @param {{ type: string }} node
     * @returns {node is AcornNode & import('estree').ClassDeclaration}
     */
    const isClassDeclaration = (node) => {
      return node.type === 'ClassDeclaration';
    };
    /**
     * @param {{ type: string }} node
     * @returns {node is AcornNode & import('estree').ExportNamedDeclaration}
     */
    const isExportNamedDeclaration = (node) => {
      return node.type === 'ExportNamedDeclaration';
    };
    
    /**
     * @param {{ type: string }} node
     * @returns {node is AcornNode & import('estree').ExportSpecifier}
     */
    const isExportSpecifier = (node) => {
      return node.type === 'ExportSpecifier';
    };
    

    I already did this in two projects and for the new one I want to do it correctly. In the veins of

    (also fwiw, I've been meaning to refactor out axios of the SDK altogether to make it as lean as possible, but lets not get ahead of ourselves there and figure this out first).

    Originally posted by @rijkvanzanten in https://github.com/directus/sdk/issues/26#issuecomment-1204381041

    I want to push the splitting of the transport forward.

    I think this would be a breaking change as I would love to generate separate bundles for each transport (to be able to mark axios as optional). But this would require changing user side import I guess (except something with dynamic imports to get the axios transport if axios is installed and no other transport is provided :thinking:).

    For backward compatibility we could let the directus constructor accept string | ITransport as first argument and deprecate passing the transport in the options object. If it is a string the constructor would try to create the axios transport (via dynamic import?) and throw if this fails (i.e. axios not available). Else the constructor parameter is just used as the transport.

    Probably the hardest part is to add the auth token in a transport agnostic way. But we could help this by pushing the responsibility for this to the developer but giving them a hand by providing a helper function for this.

    @rijkvanzanten what do you think?

    opened by fehnomenal 3
  • Proper wildcard handling for empty objects

    Proper wildcard handling for empty objects

    This PR fixes a bug where objects (usually auto-generated from an M2A field) defined as { item: { [key:string]: any } } would be cast as { item: { '*': { '*': any } } } when passing "item.." into the fields parameter on a query. This is fixed and now produces { item: any }

    opened by jonahgoldwastaken 3
  • Can not create items via the JS-SDK

    Can not create items via the JS-SDK

    Describe the Bug

    I'm trying to create one or many items by using the JS-SDK of Directus. Every time I'm calling createOne I don't retrieve the new created item but all others of the collection and the new item does not get create. The same happens when using createMany.

    When using updateOne to update a single item, everything works fine.

    To Reproduce

    1. Create new Direcuts instance
    2. Use static auth token
    3. Use directus.item() to select a collection
    4. Try to create a new item by using createOne or createMany

    Errors Shown

    No response

    What version of Directus are you using?

    9.14.5

    What version of Node.js are you using?

    16.14.2

    What database are you using?

    MySQL 8

    What browser are you using?

    Firefox

    How are you deploying Directus?

    Ubuntu server using PM2

    opened by marco910 3
  • TypeScript does not load all field paths for deeply nested collections

    TypeScript does not load all field paths for deeply nested collections

    This issue relates to the changes in the following pull request: Better query fields autocompletion and query return type based on fields value

    I have the problem that TypeScript is not able to load all possible paths due to many relationships between collections. As a result, I can't select fields that I need to select. If I type the path manually, I get an error and TypeScript doesn't know which fields were selected when it returns the query.

    screenshot

    The source is the type DotSeparated, which resolves relationship up to 5 levels deep. For collections that reference each other, this quickly leads to more than 10,000 paths due to exponential growth.

    Have you encountered this problem as well? Is there any way to tell TypeScript to load all paths? If not, I would suggest, if it is technically possible, to add the possibility, e.g. via a generic, to specify the nested paths that should be loaded preferentially. Or a possibility to solve the problem via type casting in individual cases so that the returned type of e.g.readByQuery matches the fields.

    opened by fabian-hiller 0
  • Multiple refresh calls can lead local storage empty

    Multiple refresh calls can lead local storage empty

    Originally posted as a discussion, but now I think this is a bug.

    Consider the following code

          const items = { ...localStorage };
          console.log(items);
          const token = await directus.auth.token;
          if (!token) {
            setUser(undefined);
            return;
          }
          const refresh = localStorage.getItem("auth_refresh_token");
          console.log(`refresh token: ${refresh}`);
          const refreshResult = await directus.auth.refresh();
          if (!refreshResult) {
            setUser(undefined);
          }
    

    React in dev mode executes twice to help detect any state issues. It appears that the first call to refresh succeeds, but maybe it isn't done cleaning up or something as the second fails due to the local storage being cleared for a split second. Both executions have a valid auth_refresh_token in the local storage before the call to refresh, and both return a valid token from await directus.auth.token it's just the line of localStorage.getItem("auth_refresh_token") is empty on the second call. My hypothesis is this is caused by this.resetStorage , but I'm not really sure as that call is async. I'm wrapping this in an auth provider context in an attempt to get me the current user, this promise may terminate early during a page load or something which could also be the culprit of the empty storage.

    opened by lramos15 5
  • [Typescript] Strange behaviours with relations

    [Typescript] Strange behaviours with relations

    I've found some strange typescript behavior with relations in the SDK. When querying a collection with a relation, the returned type loses the relation type, replacing it with "string" UNLESS the relation is defined as an interface. Here is an example of the issue:

    https://codesandbox.io/s/typescript-playground-export-forked-wp4wyx?file=/index.ts

    This is inconsistent with the docs, and counter to expectation since Directus only accepts a type object for the top level schema.

    opened by aidenfoxx 2
  • Type declarations not compatible with TypeScript 4.8

    Type declarations not compatible with TypeScript 4.8

    The type declarations are not compatible with TypeScript 4.8.

    Small example in TypeScript Playground

    image

    Error in line 18: image

    TS 4.8 introduced a refined behavior for strictNullChecks and and my guess is that this makes the problems surface since setting strictNullChecks to false gets rid of the type errors. But this is not recommended.

    All in all there are 17 type errors in index.d.ts when using TS 4.8.4 image

    I came across this while setting up a new Angular 15 app which uses TS 4.8.2 by default.

    Bug 
    opened by smoli 2
  • auth.login using ldap provider

    auth.login using ldap provider

    Currently it is not possible to log in using the ldap provider.

    It would only be necessary to add a parameter to the authentication method (directus.auth.login()) to add the provider to the end of the url

    auth/login -> auth/login/ldap

    Thank you!!!

    opened by efonte 1
  • Correctly type `meta` based on the query

    Correctly type `meta` based on the query

    I tried to correctly type the ManyItems.meta property based on the QueryMany.meta property.

    The adjusted types look like this:

    export type InferMetadata<T extends Item, Q extends QueryMany<T> = Record<string, any>> = Q['meta'] extends '*'
    	? ItemMetadata
    	: Pick<ItemMetadata, Exclude<Q['meta'], '*' | undefined>>;
    
    export type ManyItems<T extends Item, Q extends QueryMany<T> = Record<string, any>> = Omit<
    	{
    		data?: OneItem<T, Q>[] | null;
    		meta: InferMetadata<T, Q>;
    	},
    	undefined extends Q['meta'] ? 'meta' : ''
    >;
    

    and it works as expected at the call side:

    No meta given -> no meta returned and available image

    All meta values requested image

    Only one of the values requested image image

    But I have problems at the ItemsHandler. I added the expected meta type (M = Partial<ItemMetadata>) to the generic type signatures of the Transport class to get the correct type inside the ItemsHandler. But now e.g. readMany complains like this (the only change in line 42 to add the type):

    image

    Other methods from itemsHandler and also from other handlers have the same problem.

    Has anybody an idea how to solve this?

    Improvement 
    opened by fehnomenal 1
Releases(v10.3.1)
  • v10.3.1(Dec 22, 2022)

    What's Changed

    • Use correct key to get value in delete method of LocalStorage by @paescuj in https://github.com/directus/sdk/pull/94
    • Update package.json by @freekrai in https://github.com/directus/sdk/pull/99

    New Contributors

    • @paescuj made their first contribution in https://github.com/directus/sdk/pull/94
    • @freekrai made their first contribution in https://github.com/directus/sdk/pull/99

    Full Changelog: https://github.com/directus/sdk/compare/v10.3.0...v10.3.1

    Source code(tar.gz)
    Source code(zip)
  • v10.3.0(Nov 17, 2022)

    What's Changed

    • Allow request maxBodyLength and maxContentLength to be configurable by @licitdev in https://github.com/directus/sdk/pull/91

    Full Changelog: https://github.com/directus/sdk/compare/v10.2.0...v10.3.0

    Source code(tar.gz)
    Source code(zip)
  • v10.2.0(Nov 16, 2022)

    What's Changed

    • [Types] Make many items have non-nullable item entries by @fehnomenal in https://github.com/directus/sdk/pull/69
    • Added an AssetHandler for the Asset endpoint by @rijkvanzanten in https://github.com/directus/sdk/pull/89
    • Remove OS info by @licitdev in https://github.com/directus/sdk/pull/54
    • Add update batch items by @tenebrius in https://github.com/directus/sdk/pull/50

    New Contributors

    • @fehnomenal made their first contribution in https://github.com/directus/sdk/pull/69
    • @licitdev made their first contribution in https://github.com/directus/sdk/pull/54
    • @tenebrius made their first contribution in https://github.com/directus/sdk/pull/50

    Full Changelog: https://github.com/directus/sdk/compare/v10.1.5...v10.2.0

    Source code(tar.gz)
    Source code(zip)
  • v10.1.5(Nov 1, 2022)

    What's Changed

    • Bump @rollup/plugin-commonjs from 22.0.1 to 22.0.2 by @dependabot in https://github.com/directus/sdk/pull/32
    • fix: add type constraint for custom auth handlers by @heilmela in https://github.com/directus/sdk/pull/52
    • Proper wildcard handling for empty objects by @jonahgoldwastaken in https://github.com/directus/sdk/pull/60
    • Fix typing on deep queries by @jonahgoldwastaken in https://github.com/directus/sdk/pull/59
    • Fix up typings for query fields parameter by @jonahgoldwastaken in https://github.com/directus/sdk/pull/58
    • Explicitely set type definitions for exports by @echocrow in https://github.com/directus/sdk/pull/67
    • Remove caret from packageManager package.json field by @nickrum in https://github.com/directus/sdk/pull/74
    • Don't modify the return type on a read query without specified fields by @jonahgoldwastaken in https://github.com/directus/sdk/pull/63
    • Fixing fields handler output structure by @br41nslug in https://github.com/directus/sdk/pull/77
    • feat: nearer-to-complete types by @monbrey in https://github.com/directus/sdk/pull/78
    • Properly handle optional and required fields by @jonahgoldwastaken in https://github.com/directus/sdk/pull/72
    • fix options.transport usage by @drico in https://github.com/directus/sdk/pull/80

    New Contributors

    • @heilmela made their first contribution in https://github.com/directus/sdk/pull/52
    • @echocrow made their first contribution in https://github.com/directus/sdk/pull/67
    • @nickrum made their first contribution in https://github.com/directus/sdk/pull/74
    • @br41nslug made their first contribution in https://github.com/directus/sdk/pull/77
    • @monbrey made their first contribution in https://github.com/directus/sdk/pull/78
    • @drico made their first contribution in https://github.com/directus/sdk/pull/80

    Full Changelog: https://github.com/directus/sdk/compare/v10.1.4...v10.1.5

    Source code(tar.gz)
    Source code(zip)
  • v10.1.4(Aug 5, 2022)

    What's Changed

    • Avoid overriding filter in readMany handler by @erickjth in https://github.com/directus/sdk/pull/30

    New Contributors

    • @erickjth made their first contribution in https://github.com/directus/sdk/pull/30

    Full Changelog: https://github.com/directus/sdk/compare/v10.1.3...v10.1.4

    Source code(tar.gz)
    Source code(zip)
  • v10.1.3(Aug 5, 2022)

    What's Changed

    • Remove params from the update relation API by @bobbyphilip in https://github.com/directus/sdk/pull/27

    New Contributors

    • @bobbyphilip made their first contribution in https://github.com/directus/sdk/pull/27

    Full Changelog: https://github.com/directus/sdk/compare/v10.1.2...v10.1.3

    Source code(tar.gz)
    Source code(zip)
  • v10.1.2(Jul 28, 2022)

    What's Changed

    • Better query fields autocompletion and query return type based on fields value by @jonahgoldwastaken in https://github.com/directus/sdk/pull/22
    • Bump ts-node from 10.8.2 to 10.9.1 by @dependabot in https://github.com/directus/sdk/pull/21
    • Bump rollup from 2.76.0 to 2.77.0 by @dependabot in https://github.com/directus/sdk/pull/20
    • Bump jest from 28.1.2 to 28.1.3 by @dependabot in https://github.com/directus/sdk/pull/19
    • Bump ts-jest from 28.0.5 to 28.0.7 by @dependabot in https://github.com/directus/sdk/pull/17
    • Bump jest-environment-jsdom from 28.1.2 to 28.1.3 by @dependabot in https://github.com/directus/sdk/pull/18
    • Bump @types/jest from 28.1.4 to 28.1.6 by @dependabot in https://github.com/directus/sdk/pull/23
    • Bump nock from 13.2.8 to 13.2.9 by @dependabot in https://github.com/directus/sdk/pull/24
    • Bump rollup from 2.77.0 to 2.77.2 by @dependabot in https://github.com/directus/sdk/pull/25

    New Contributors

    • @jonahgoldwastaken made their first contribution in https://github.com/directus/sdk/pull/22
    • @dependabot made their first contribution in https://github.com/directus/sdk/pull/21

    Full Changelog: https://github.com/directus/sdk/compare/v10.1.1...v10.1.2

    Source code(tar.gz)
    Source code(zip)
  • v10.1.1(Jul 15, 2022)

    What's Changed

    • Add open api spec to SDK by @craigharman in https://github.com/directus/sdk/pull/15

    New Contributors

    • @craigharman made their first contribution in https://github.com/directus/sdk/pull/15

    Full Changelog: https://github.com/directus/sdk/compare/v10.0.1...v10.1.1

    Source code(tar.gz)
    Source code(zip)
  • v10.1.0(Jul 14, 2022)

  • v10.0.1(Jul 9, 2022)

    What's Changed

    • Upgrade dependencies by @rijkvanzanten in https://github.com/directus/sdk/pull/13

    Full Changelog: https://github.com/directus/sdk/compare/v10.0.0...v10.0.1

    Source code(tar.gz)
    Source code(zip)
  • v10.0.0(Jul 9, 2022)

    What's Changed

    • Refactor auth token in the SDK to be async by @rijkvanzanten in https://github.com/directus/sdk/pull/9

    Full Changelog: https://github.com/directus/sdk/compare/v9.14.2...v10.0.0

    Migration from v9

    Replace any usage of sdk.auth.token to be async:

    // Before
    const token = sdk.auth.token;
    
    // After
    const token = await sdk.auth.token;
    
    Source code(tar.gz)
    Source code(zip)
  • v9.14.2(Jul 9, 2022)

    What's Changed

    • Add linter setup by @rijkvanzanten in https://github.com/directus/sdk/pull/5

    New Contributors

    • @rijkvanzanten made their first contribution in https://github.com/directus/sdk/pull/5

    Full Changelog: https://github.com/directus/sdk/commits/v9.14.2

    Source code(tar.gz)
    Source code(zip)
Owner
Directus
An instant no-code App and dynamic API for any SQL database.
Directus
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling rapid development of iofod extensions through the SDK.

iofod-sdk English | 简体中文 The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling

iofod, Inc. 47 Oct 17, 2022
Movehat is a TypeScript SDK for Move on Sui built on top of Sui's TypeScript SDK and our fork of Ian Macalinao's `move-ts`.

Movehat Movehat is a TypeScript SDK for Move on Sui built on top of Sui's TypeScript SDK and our fork of Ian Macalinao's move-ts. Movehat aspires to b

Pentagon 10 Sep 30, 2022
Official repository for the Orbis SDK.

Build decentralized social apps with the Orbis SDK By using the Orbis SDK, developers can build their own decentralized social apps or add a decentral

Orbis 45 Dec 31, 2022
Directus Hook Extension: Version Control Changelog

A Directus hook extension to push user written change summaries (from a singleton collection text field) to a changelog in a VCS server

BIX Digital Lab 11 Nov 27, 2022
Directus dataprovider package for refine.

refine-directus Directus dataprovider package for refine. About refine offers lots of out-of-the box functionality for rapid development, without comp

Vivek Palanisamy 15 Dec 27, 2022
An extension to get randomized results from directus.

Directus Extension Randomized Results As the name suggests this extension will enable Randomized results mirroring the Directus /items/:collection end

Brainslug 4 Oct 19, 2022
Custom endpoint to backup the PG database and upload the `.dump` to Directus.

Directus Backup Endpoint Custom Directus endpoint to backup Postgres database using pg_dump and upload the .dump file into Directus files. Usage Clone

Guilherme Oliveira 7 Dec 21, 2022
Custom operation to backup the PG database and upload the .dump to Directus.

Directus Backup Operation Custom Directus operation to backup Postgres database using pg_dump and upload the .dump file into Directus storage. Prerequ

Guilherme Oliveira 7 Dec 21, 2022
New base script bot wa by Ramdani Official, don't forget to subscribe youtube Ramdani Official.

Requirements • Installation • Thanks to • Official Group Bot • Donate Information bahasa Indonesia Ramdani Botz V17 adalah bot yang di ciptakan oleh R

Ramdani Official 22 Nov 1, 2022
microCMS JavaScript SDK.

microCMS JavaScript SDK It helps you to use microCMS from JavaScript and Node.js applications. Getting Started Install Install npm package. $ npm inst

Wanta Inc 107 Dec 31, 2022
Anagolay Network Javascript SDK written in Typescript

Anagolay Network Javascript SDK written in Typescript. This repo will contain the bindings to Anagolay Network with the sane defaults for pallet usage

Anagolay Network 4 Nov 26, 2022
Codemod scripts to update AWS SDK for JavaScript APIs.

aws-sdk-js-codemod This repository contains a collection of codemod scripts for use with JSCodeshift that help update AWS SDK for JavaScript APIs. The

Amazon Web Services - Labs 17 Jan 2, 2023
It's a javascript Class which contains utility methods that simplify working with google maps web SDK

About GoogleMapsJSHelper It's a javascript Class which contains utility methods that simplify working with google maps web SDK Note: i used ES7 Class

Sami Alateya 6 Jul 23, 2022
A JavaScript (and TypeScript) SDK for the ScreenshotOne.com API to take screenshots of any URL

jssdk An official Screenshot API client for JavaScript and TypeScript. It takes minutes to start taking screenshots. Just sign up to get access and se

ScreenshotOne.com 7 Oct 15, 2022
Unofficial port of the Sentry SDK for JavaScript to Deno.

Sentry_deno This is an unofficial port of the Sentry SDK (@sentry/browser) to Deno. import * as Sentry from "https://deno.land/x/sentry_deno/main.ts";

Geert-Jan Zwiers 11 Aug 11, 2022
BotCity Maestro SDK - JavaScript

BotCity Maestro SDK - Javascript « Explore Framework docs Summary Summary ?? Computer-vision based UI Automation ?? Getting Started ?? Prerequisites ?

BotCity - Automation for Developers 9 Sep 6, 2022
Official moon configurations for popular JavaScript developer tooling.

moon development configs This repository is a collection of moon owned and maintained configurations and presets for common developer tools -- primari

moonrepo 8 Nov 10, 2022