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

@plugandwork/core-js

v0.0.34

Published

Core-js est un client développé par plugandwork pour l'integration de l'API plugandwork dans des applications javascript. Core-js est une librairie multiplateforme, elle peut être utilisée dans des applications nodejs et web.

Downloads

94

Readme

core-js

Core-js est un client développé par plugandwork pour l'integration de l'API plugandwork dans des applications javascript. Core-js est une librairie multiplateforme, elle peut être utilisée dans des applications nodejs et web.

Installation

Core-js est disponible sur npm et vous pouvez l'installer en tant que dépendance de votre projet.

npm install @plugandwork/core-js

Usage

La première étape pour commencer à utiliser le client est de l'instancier avec, au minimum, le endpoint de l'api plugandwork. Vous pouvez également passer d'autres options, comme un token qui servira à authentifier les requêtes envoyées à l'api. Ce token n'est pas obligatoire car il pourra être récupéré grâce à des identifiants plugandwork (login).

import Client from "@plugandwork/core-js";

const client = new Client({
  endpoint: "https://api.plugandwork.fr", // replace with you api endpoint
});

Une fois que le client a terminé son execution, vous pouvez le fermer grâce à la méthode client.close()

Configuration

Vous pouvez modifier la configuration du client même une fois instancié grâce à la méthode setOptions.

type ClientOptions = {
  endpoint: string;
  token?: string;
  ssl?: boolean;
};

const client = new Client({
  endpoint: "https://api.plugandwork.fr",
  token: "...",
});

client.setOption({
  token: "...",
});

Utilisation des modèles

La plupart des méthodes de l'api (create, read, update, delete, etc.) sont des méthodes héritées de la classe Model. Par exemple, pour récupérer une liste de documents, la méthode à appeler sera Doc.getList, Doc héritant de Model. Pour fonctionner, la classe Model a besoin d'être lié à un client:

  • Soit grâce à la méthode Model.withClient(client)
  • Soit en définissant un client par défaut grâce à la méthode client.declareGlobally()

Exemple avec Model.prototype.withClient

import { Doc } from "@plugandwork/core-js";

// ...

const listDocs = await Doc.withClient(client).getList();

Exemple avec Client.prototype.declareGlobally

import { Doc, Space } from "@plugandwork/core-js";

// ...

client.declareGlobally();

const listDocs = await Doc.getList();
const listSpaces = await Space.getList(); // also works thanks to client.declareGlobally()

Model

Modèles disponibles :

  • App
  • Batch
  • Bloc
  • Context
  • Dataset
  • Doc
  • Family
  • Folder
  • Group
  • Message
  • Notification
  • Space
  • Task
  • User
  • View

Lecture

Model.getList

Vous pouvez récupérer la liste des instances d'un modèle grâce à la méthode Model.getList. Les paramètres de la méthode sont ceux envoyés à l'api et sont décrits dans la documentation de l'api à l'adresse suivante : [endpoint]/api/swagger/index.html

const list = await Doc.getList({
  per_page: 10,
  page: 2,
});
console.log(list.length); // 10

Model.get

Si vous avez besoin de récupérer seulement une instance d'un modèle, vous pouvez utiliser la méthode Model.get. Cette méthode prend en paramètres soit l'id de l'instance à récupérer, soit un objet contenant les paramètres de la requête.

const doc = await Doc.get("...");
console.log(doc.id); // ...

const doc = await Doc.get({
  title: "test",
  page: 2,
});
console.log(doc.title); // test

Création

Model.create

Vous pouvez créer une nouvelle instance d'un modèle grâce à la méthode Model.create. Cette méthode prend en paramètres le payload de l'objet a crééer sous la forme d'un objet ou d'une instance de FormData.

const doc = await Doc.create({ title: "test" });
console.log(doc.id); // ...
console.log(doc.title); // test

Modification

Model.prototype.update

Vous pouvez modifier une instance d'un modèle grâce à la méthode Model.prototype.update. Cette méthode prend en paramètres le payload de l'objet à modifier sous la forme d'un objet ou d'une instance de FormData.

const doc = await Doc.create({ title: "test1" });
const updatedDoc = await doc.update({ title: "test2" });
console.log(updatedDoc.title); // test2

The updated document returned by this method is the same as the document on which the method was called. In other words, the method modifies the document on which it is called. In the example above:

console.log(doc === updatedDoc); // true

Suppression

Model.prototype.delete

Vous pouvez supprimer une instance d'un modèle grâce à la méthode Model.prototype.delete.

const doc = await Doc.create({ title: "test1" });
const id = doc.id;
await doc.delete();
console.log(doc.id); // Throw "This element has been deleted"
await Doc.get(id); // null

Mise en forme

Model.prototype.toJSON

Cette méthode retourne un objet contenant les champs de l'instance. Le retour de cette méthode sera donc une instance de la classe Object et non de la classe Model.

const json = doc.toJSON();
console.log(json instanceof Doc); // false
console.log(json instanceof Object); // true
console.log(json.title); // test
await json.update({ ... }); // Throw an error as json is not an instance of Model

get field

Vous pouvez récupérer la valeur d'un champ d'une instance grâce à la méthode Model.prototype.get. Cette méthode prend en paramètre le nom du champ à récupérer.

const title = doc.get("title");
console.log(title); // test

Cette méthode est attribuée par défaut au prototype de la classe Model afin de simplifier son utilisation. Ainsi, doc.title est l'équivalent de doc.get("title").

Listes en temps réel avec ContextList

Les contextes plugandwork permettent de définir le scope d'une liste grâce à une requête (du même type que celle utilisée dans Model.getList). Le contexte observe alors les modifications des instances correspondant à la requête et envoie des évènements à chaque modification via un websocket. Ce comportement est embarqué dans la classe ContextList, qui étend la classe Array. ContextList instancie un contexte à partir d'une requête donnée en paramètres et met à jour la liste lorsqu'un évènement est recu.

import { ContextList, Doc } from "@plugandwork/core-js";

const title = generateRandomString();

const contextList = await ContextList.create(Doc, {
  search_params: {
    title,
  },
  options: {
    sort: {
      created_at: -1,
    },
  },
});

const doc = await Doc.create({
  title,
});

await new Promise((resolve) => setTimeout(resolve, 500)); // we need to wait for the event to be received

console.log(contextList.rows.includes(doc)); // true

Méthodes du client

Client.prototype.getToken

Cette méthode permet de récupérer un token d'authentification à partir d'identifiants plugandwork. Le token est assigné aux options du client et est utilisé pour toutes les requêtes faites par le client.

import Client from "@plugandwork/core-js";

const client = new Client({
  endpoint: "https://api.plugandwork.fr",
});

await client.getToken({
  username: "...",
  password: "...",
});

console.log(client.options.token); // Token has been assigned

Exemples

Création d'un document

import Client, { Doc } from "@plugandwork/core-js";

const client = new Client( ... );
client.declareGlobally(); // or use Model.withClient instead

const formData = new FormData();

const file = fs.createReadStream("path/to/file");
formData.append("file", file);
formData.append("title", "Lorem ipsum");

const doc = await Doc.create(formData, attributes);

Récupération d'une liste de documents

import Client, { Doc } from "@plugandwork/core-js";

const client = new Client( ... );
client.declareGlobally(); // or use Model.withClient instead

const list = await Doc.getList({
  space_id: "...", // Will match all documents in the space with id "..."
  per_page: 10, // Number of documents per page
  page: 2, // Page number
});

Récupération d'un espace de travail

import Client, { Space } from "@plugandwork/core-js";

const client = new Client( ... );
client.declareGlobally(); // or use Model.withClient instead

const space = await Space.get("..."); // Will match the space with id "..."

[Vue] - Composant pour l'affichage de documents

<template>
  <div>
    <h2>Documents</h2>
    <ul>
      <li v-for="doc in documents" :key="doc.id">{{ doc.title }}</li>
    </ul>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from "vue";
import Client, { Doc } from "@plugandwork/core-js";

export default {
  setup() {
    const documents = ref([]);
    const newDocTitle = ref("");
    const client = new Client( ... );

    client.declareGlobally();

    const fetchDocuments = async () => {
      documents.value = await Doc.getList({
        per_page: 10,
        page: 1,
      });
    };

    onMounted(() => {
      fetchDocuments();
    });

    onUnmounted(() => {
      client.close();
    });

    return {
      documents,
      newDocTitle,
    };
  },
};
</script>

[Vue] - Utilisation de ContextList dans un composant Vue.js

<template>
  <div>
    <h2>Documents en temps réel</h2>
    <ul>
      <li v-for="doc in documents" :key="doc.id">{{ doc.title }}</li>
    </ul>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from "vue";
import Client, { Doc, ContextList } from "@plugandwork/core-js";

export default {
  setup() {
    const documents = ref([]);
    const client = new Client( ... );

    client.declareGlobally();

    let contextList;

    const initContextList = async () => {
      contextList = await ContextList.create(Doc, {
        search_params: {
          // Vos critères de recherche ici
        },
        options: {
          sort: {
            created_at: -1,
          },
        },
      });

      documents.value = contextList.rows;

      contextList.subscribe(() => {
        documents.value = [...contextList.rows];
      });
    };

    onMounted(() => {
      initContextList();
    });

    onUnmounted(() => {
      contextList?.destroy();
      client.close();
    });

    return {
      documents,
    };
  },
};
</script>

[React] - Initialisation du client et récupération de documents

import React, { useState, useEffect } from "react";
import Client, { Doc } from "@plugandwork/core-js";

const DocumentList = () => {
  const [documents, setDocuments] = useState([]);

  useEffect(() => {
    const client = new Client( ... );

    client.declareGlobally();

    const fetchDocuments = async () => {
      const docs = await Doc.getList({
        per_page: 10,
        page: 1,
      });
      setDocuments(docs);
    };

    fetchDocuments();

    return () => {
      client.close();
    };
  }, []);

  return (
    <ul>
      {documents.map((doc) => (
        <li key={doc.id}>{doc.title}</li>
      ))}
    </ul>
  );
};

export default DocumentList;

[React] - Utilisation de ContextList pour une liste en temps réel

import React, { useState, useEffect } from "react";
import Client, { Doc, ContextList } from "@plugandwork/core-js";

const RealtimeDocumentList = () => {
  const [documents, setDocuments] = useState([]);

  useEffect(() => {
    const client = new Client( ... );

    client.declareGlobally();

    let contextList;

    const initContextList = async () => {
      contextList = await ContextList.create(Doc, {
        search_params: {
          // Vos critères de recherche ici
        },
        options: {
          sort: {
            created_at: -1,
          },
        },
      });

      setDocuments(contextList.rows);

      contextList.subscribe(() => {
        setDocuments([...contextList.rows]);
      });
    };

    initContextList();

    return () => {
      contextList?.destroy();
      client.close();
    };
  }, []);

  return (
    <ul>
      {documents.map((doc) => (
        <li key={doc.id}>{doc.title}</li>
      ))}
    </ul>
  );
};

export default RealtimeDocumentList;