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

@datafoodconsortium/connector

v1.0.0-alpha.8

Published

The Data Food Consortium (DFC) Connector is a tool to help you to integrate the DFC standard within you application.

Downloads

24

Readme

Data Food Consortium Connector

The Data Food Consortium (DFC) Connector is a tool to help you to integrate the DFC standard within you application.

Each concept of the DFC ontology can be manipulated with the help of the corresponding class supplied by the connector.

This connector will also help you to import and export data so you can exchange information with other DFC standard compliant platforms.

The Data Food Consortium project (DFC) aims to provide interoperability between food supply chain platforms.

Get started

Install

You can install the connector with the following command: npm i @datafoodconsortium/connector.

Import and use the connector

Then in you JS file, import the newly installed connector:

import { Connector } from '@datafoodconsortium/connector';

const connector = new Connector();

Load the taxonomies

You can then load our different SKOS taxonomies providing the corresponding JSON-LD files:

connector.loadMeasures(File.read("/path/to/measures.json"));
connector.loadFacets(File.read("/path/to/facets.json"));
connector.loadProductTypes(File.read("/path/to/productTypes.json"));
connector.loadVocabulary(File.read("/path/to/vocabulary.json"));

These taxonomies are accessible directly from the connector, like:

// Example of a facet
const fruit = connector.FACETS.PARTORIGIN.PLANTPARTORIGIN.FRUIT;

// Example of an measure
const kilogram = connector.MEASURES.UNIT.QUANTITYUNIT.KILOGRAM;

// Example of a product type
const tomato = connector.PRODUCT_TYPES.VEGETABLE.TOMATO.ROUND_TOMATO;

// Example of a transformation type
const combines = connector.VOCABULARY.TRANSFORMATIONTYPE.COMBINES;

Object creation

Remark: each newly created object will be saved into the store provided to the Connector. This store will allow you to access to the referenced objects more easily. You can disable this behavior passing the doNotStore: true parameter when constructing the objects.

Call the creation methods from the connector:

import { Connector } from "@datafoodconsortium/connector";

const quantity = connector.createQuantity({ 
    value: 1.2, 
    unit: kilogram
});

const allergenCharacteristic = connector.createAllergenCharacteristic({ 
    value: 1, 
    unit: kilogram, 
    allergenDimension: connector.MEASURES.DIMENSION.ALLERGENDIMENSION.PEANUTS 
});

const nutrientCharacteristic = connector.createNutrientCharacteristic({ 
    value: 10, 
    unit: gram, 
    nutrientDimension: connector.MEASURES.DIMENSION.NUTRIENTDIMENSION.CALCIUM 
});

const physicalCharacteristic = connector.createPhysicalCharacteristic({ 
    value: 100, 
    unit: gram, 
    physicalDimension: connector.MEASURES.DIMENSION.PHYSICALDIMENSION.WEIGHT 
});

const catalogItem = connector.createCatalogItem({ 
    semanticId: "http://myplatform.com/catalogItem" 
});

let suppliedProduct = connector.createSuppliedProduct({
    semanticId: "http://myplatform.com/tomato",
    description: "Awesome tomato",
    productType: connector.PRODUCT_TYPES.VEGETABLE.TOMATO.ROUND_TOMATO, 
    quantity: quantity,
    totalTheoreticalStock: 2.23,
    alcoholPercentage: 0, 
    lifetime: "a week", 
    claims: [connector.FACETS.CLAIM.NUTRITIONALCLAIM.NOADDEDSUGARS], 
    usageOrStorageConditions: "free text", 
    allergenCharacteristics: [allergenCharacteristic],
    nutrientCharacteristics: [nutrientCharacteristic],
    physicalCharacteristics: [physicalCharacteristic],
    geographicalOrigin: connector.FACETS.TERRITORIALORIGIN.EUROPE.FRANCE.CENTREVALLOIRE,
    catalogItems: [catalogItem], 
    certifications: [connector.FACETS.CERTIFICATION.ORGANICLABEL.ORGANIC_AB, connector.FACETS.CERTIFICATION.ORGANICLABEL.ORGANIC_EU],
    natureOrigin: [connector.FACETS.NATUREORIGIN.PLANTORIGIN],
    partOrigin: [connector.FACETS.PARTORIGIN.PLANTPARTORIGIN.FRUIT]
});

Remark: Except for anonymous objects (blank nodes), the semanticId constructor parameter is mandatory. All the other parameters are optional.

Available creation methods:

  • IConnector:createAddress(parameters): IAddress;
  • IConnector:createAllergenCharacteristic(parameters): IAllergenCharacteristic;
  • IConnector:createCatalog(parameters): ICatalog;
  • IConnector:createCatalogItem(parameters): ICatalogItem;
  • IConnector:createCustomerCategory(parameters): ICustomerCategory;
  • IConnector:createEnterprise(parameters): IEnterprise;
  • IConnector:createNutrientCharacteristic(parameters): INutrientCharacteristic;
  • IConnector:createOffer(parameters): IOffer;
  • IConnector:createOrder(parameters): IOrder;
  • IConnector:createOrderLine(parameters): IOrderLine;
  • IConnector:createPerson(parameters): IPerson;
  • IConnector:createPhysicalCharacteristic(parameters): IPhysicalCharacteristic;
  • IConnector:createPrice(parameters): IPrice;
  • IConnector:createQuantity(parameters): IQuantity;
  • IConnector:createSaleSession(parameters): ISaleSession;
  • IConnector:createSuppliedProduct(parameters): ISuppliedProduct;
  • IConnector:createPlannedTransformation(parameters);
  • IConnector:createPlannedConsumptionFlow(parameters);
  • IConnector:createPlannedProductionFlow(parameters);

Object accessors and mutators

Read object properties (accessor)

You can read the properties of an objet using getter methods. Some are synchronous while other are asynchronous.

Accessing litterals is synchronous

// Don't need to await when getting literral values like string, number or boolean.
suppliedProduct.getDescription();

Accessing referenced objects is asynchronous

The previous method returned a simple string. But an object ofen contains other objects. In the semantic web, every object has its own URI. So we will store only a reference to these contained objects using their URI. They are called "referenced objects".

To access a referenced object using the connector you just have to await for it like:

// You must await when getting referenced objects.
const addresses: IAddress[] = await person.getLocalizations();

Remark: Running the previous code sample will trigger a call to the fetch function of the connector. If the referenced object it is not already in the connector store, it will be downloaded from the network.

Change object properties (mutator)

If you want to change a property after the creation of the object, you can use its proper setter method like:

// Set the quantity of the product
suppliedProduct.setQuantity(connector.createQuantity(kilogram, 2.6));

You can also add a value to properties that are array:

// Add a new certification to the product
suppliedProduct.addCertification(connector.FACETS.CERTIFICATION.LOCALLABEL.AOC_FR);

Export objects

With the Connector, you can export DFC object(s). The default exporter exports objects to JSON-LD:

console.log(await connector.export([suppliedProduct]));

Remark: the export function accepts an "options" parameter that can be use to pass a custom exporter, input and output contexts:

options?: {
    exporter?: IConnectorExporter;
    inputContext?: any;
    outputContext?: any;
}

This will output DFC compliant valid JSON-LD like:

{
  "@context": "http://www.datafoodconsortium.org/ontologies/context.json",
  "@graph": [
    {
      "@id": "_:b1",
      "@type": "dfc-b:QuantitativeValue",
      "dfc-b:hasUnit": "dfc-m:Kilogram",
      "dfc-b:value": "1.2"
    },
    {
      "@id": "_:b2",
      "@type": "dfc-b:AllergenCharacteristic",
      "dfc-b:hasAllergenDimension": "dfc-m:Peanuts",
      "dfc-b:hasUnit": "dfc-m:Kilogram",
      "dfc-b:value": "1"
    },
    {
      "@id": "_:b4",
      "@type": "dfc-b:NutrientCharacteristic",
      "dfc-b:hasNutrientDimension": {
        "@id": "dfc-m:Calcium"
      },
      "dfc-b:hasUnit": "dfc-m:Gram",
      "dfc-b:value": "10"
    },
    {
      "@id": "_:b6",
      "@type": "dfc-b:PhysicalCharacteristic",
      "dfc-b:hasPhysicalDimension": "dfc-m:Weight",
      "dfc-b:hasUnit": "dfc-m:Gram",
      "dfc-b:value": "100"
    },
    {
      "@id": "http://myplatform.com/tomato",
      "@type": "dfc-b:SuppliedProduct",
      "dfc-b:alcoholPercentage": "0",
      "dfc-b:description": "Awesome tomato",
      "dfc-b:hasAllergenCharacteristic": {
        "@id": "_:b2"
      },
      "dfc-b:hasCertification": [
        {
          "@id": "dfc-f:Organic-AB"
        },
        {
          "@id": "dfc-f:Organic-EU"
        }
      ],
      "dfc-b:hasClaim": "dfc-f:NoAddedSugars",
      "dfc-b:hasGeographicalOrigin": "dfc-f:CentreValLoire",
      "dfc-b:hasNatureOrigin": {
        "@id": "dfc-f:PlantOrigin"
      },
      "dfc-b:hasNutrientCharacteristic": {
        "@id": "_:b4"
      },
      "dfc-b:hasPartOrigin": {
        "@id": "dfc-f:Fruit"
      },
      "dfc-b:hasPhysicalCharacteristic": {
        "@id": "_:b6"
      },
      "dfc-b:hasQuantity": "_:b1",
      "dfc-b:hasType": "dfc-pt:round-tomato",
      "dfc-b:lifetime": "a week",
      "dfc-b:referencedBy": "http://myplatform.com/catalogItem",
      "dfc-b:totalTheoreticalStock": "2.23",
      "dfc-b:usageOrStorageCondition": "free text"
    }
  ]
}

Import objects

The DFC Connector provides method to import data. The default importer imports JSON-LD data.

To import objects from JSON-LD, use:

const objects: Semanticable[] = await connector.import(jsonAsAString));

Remark: the import function accepts an "options" parameter that can be use to fit to your needs:

options?: { 
  only?: string; // pass a RDF type to filter the results.
  limit?: number; // limit the results to a the n first elements.
  importer?: IConnectorImporter; // pass an alternate importer to process the data.
  factory?: IConnectorFactory; // pass an alternate factory to create the imported elements.
  doNotStore?: boolean; // don't store any of the imported elements.
}

For example, to get the first 3 Order of some imported data use:

await connector.import(jsonAsAString, { only: connector.TERMS.ORDER, limit: 3 });

You can also get a single element using the importOne helper method:

const Semanticable | undefined = await connector.importOne(jsonAsAString);

You can pass the only option to target one type using the importOneTyped method:

const order: string = "http://www.datafoodconsortium.org/ontologies/DFC_BusinessOntology.owl#Order";
const IOrder | undefined = await connector.importOneTyped<IOrder>(jsonAsAString, { only: order });

Configure

You can adapt different components of the connector to your needs with the following connector methods:

// Set the function that will fetch the referenced objects when importing data.
Connector:setDefaultFetchFunction(fetch: (semanticId: string) => Promise<string>): void;

// Set the object that will store the imported objects.
Connector:setDefaultStore(store: IConnectorStore): void;

// Set the object that will export the objects.
Connector:setDefaultExporter(exporter: IConnectorExporter);

// Set the object that will import the objects.
Connector:setDefaultImporter(importer: IConnectorImporter);

// Set the object used to create new instances.
Connector:setDefaultFactory(factory: IConnectorFactory);

Reference

Address

IConnector:createAddress(parameters): IAddress

parameters: {
  semanticId: string, 
  street?: string, 
  postalCode?: string, 
  city?: string, 
  country?: string,
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createAddress(parameters): IAddress

parameters: {
  other: IAddress,
  doNotStore?: boolean // if true, do not save the object into the connector store
}

AllergenCharacteristic

IConnector:createAllergenCharacteristic(parameters): IAllergenCharacteristic

parameters: {
  unit?: IUnit, 
  value?: number, 
  allergenDimension?: IAllergenDimension,
}

IConnector:createAllergenCharacteristic(parameters): IAllergenCharacteristic

parameters: {
  other: IAllergenCharacteristic // construct the object by copy
}

Catalog

IConnector:createCatalog(parameters): ICatalog

parameters: {
  semanticId: string, 
  maintainers?: IEnterprise[], 
  items?: ICatalogItem[],
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createCatalog(parameters): ICatalog

parameters: {
  other: ICatalog, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

CatalogItem

IConnector:createCatalogItem(parameters): ICatalogItem

parameters: {
  semanticId: string, 
  product?: ISuppliedProduct, 
  sku?: string, 
  stockLimitation?: number, 
  offers?: IOffer[], 
  catalogs?: ICatalog[],
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createCatalogItem(parameters): ICatalogItem

parameters: {
  other: ICatalogItem, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

CustomerCategory

IConnector:createCustomerCategory(parameters): ICustomerCategory

parameters: {
  semanticId: string, 
  description?: string,
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createCustomerCategory(parameters): ICustomerCategory

parameters: {
  other: ICustomerCategory, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

Enterprise

IConnector:createEnterprise(parameters): IEnterprise

parameters: {
  semanticId: string, 
  localizations?: IAddress[], 
  description?: string, 
  vatNumber?: string, 
  customerCategories?: ICustomerCategory[], 
  catalogs?: ICatalog[], 
  catalogItems?: ICatalogItem[], 
  suppliedProducts?: ISuppliedProduct[],
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createEnterprise(parameters): IEnterprise

parameters: {
  other: IEnterprise, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

NutrientCharacteristic

IConnector:createNutrientCharacteristic(parameters): INutrientCharacteristic

parameters: {
  unit?: IUnit, 
  value?: number, 
  nutrientDimension?: INutrientDimension
}

IConnector:createNutrientCharacteristic(parameters): INutrientCharacteristic

parameters: {
  other: INutrientCharacteristic // construct the object by copy
}

Offer

IConnector:createOffer(parameters): IOffer

parameters: {
  semanticId: string, 
  offeredItem?: ICatalogItem, 
  offeredTo?: ICustomerCategory, 
  price?: IPrice, 
  stockLimitation?: number,
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createOffer(parameters): IOffer

parameters: {
  other: IOffer, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

Order

IConnector:createOrder(parameters): IOrder

parameters: {
  semanticId: string, 
  number?: string, 
  date?: string, 
  saleSession?: ISaleSession, 
  client?: IAgent, 
  lines?: IOrderLine[],
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createOrder(parameters): IOrder

parameters: {
  other: IOrder, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

OrderLine

IConnector:createOrderLine(parameters): IOrderLine

parameters: {
  semanticId: string, 
  quantity?: number, 
  price?: IPrice, 
  offer?: IOffer, 
  order?: IOrder,
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createOrderLine(parameters): IOrderLine

parameters: {
  other: IOrderLine, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

Person

IConnector:createPerson(parameters): IPerson

parameters: {
  semanticId: string, 
  firstName?: string, 
  lastName?: string, 
  localizations?: IAddress[], 
  organizations?: IEnterprise[],
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createPerson(parameters): IPerson

parameters: {
  other: IPerson, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

PhysicalCharacteristic

IConnector:createPhysicalCharacteristic(parameters): IPhysicalCharacteristic

parameters: {
  unit?: IUnit, 
  value?: number, 
  physicalDimension?: IPhysicalDimension
}

IConnector:createPhysicalCharacteristic(parameters): IPhysicalCharacteristic

parameters: {
  other: IPhysicalCharacteristic // construct the object by copy
}

PlannedConsumptionFlow

IConnector:createPlannedConsumptionFlow(parameters);

parameters: {
  doNotStore?: boolean, 
  semanticId?: string, 
  other?: Semanticable, 
  quantity?: IQuantity, 
  transformation?: IPlannedTransformation, 
  product?: IDefinedProduct
}

PlannedProductionFlow

IConnector:createPlannedProductionFlow(parameters);

parameters: {
  doNotStore?: boolean, 
  semanticId?: string, 
  other?: Semanticable, 
  quantity?: IQuantity, 
  transformation?: IPlannedTransformation, 
  product?: ISuppliedProduct
}

PlannedTransformation

IConnector:createPlannedTransformation(parameters);

parameters: {
  doNotStore?: boolean, 
  semanticId?: string,
  other?: Semanticable, 
  transformationType?: ISKOSConcept, 
  consumptionFlow?: IPlannedConsumptionFlow, 
  productionFlow?: IPlannedProductionFlow
}

Price

IConnector:createPrice(parameters): IPrice

parameters: {
  value?: number, 
  vatRate?: number, 
  unit?: IUnit
}

IConnector:createPrice(parameters): IPrice

parameters: {
  other: IPrice // construct the object by copy
}

Quantity

IConnector:createQuantity(parameters): IQuantity

parameters: {
  unit?: IUnit, 
  value?: number
}

IConnector:createQuantity(parameters): IQuantity

parameters: {
  other: IQuantity // construct the object by copy
}

SaleSession

IConnector:createSaleSession(parameters): ISaleSession

parameters: {
  semanticId: string, 
  beginDate?: string, 
  endDate?: string, 
  quantity?: number, 
  offers?: IOffer[],
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createSaleSession(parameters): ISaleSession

parameters: {
  other: ISaleSession, // construct the object by copy
  doNotStore?: boolean // if true, do not save the object into the connector store
}

SuppliedProduct

IConnector:createSuppliedProduct(parameters): ISuppliedProduct

parameters: {
  semanticId: string, 
  name?: string, 
  description?: string, 
  productType?: IProductType, 
  quantity?: IQuantity, 
  alcoholPercentage?: number, 
  lifetime?: string, 
  claims?: IClaim[], 
  usageOrStorageConditions?: string, 
  allergenCharacteristics?: IAllergenCharacteristic[], 
  nutrientCharacteristics?: INutrientCharacteristic[], 
  physicalCharacteristics?: IPhysicalCharacteristic[], 
  geographicalOrigin?: IGeographicalOrigin, 
  catalogItems?: ICatalogItem[], 
  certifications?: ICertification[], 
  natureOrigin?: INatureOrigin[], 
  partOrigin?: IPartOrigin[], 
  totalTheoreticalStock?: number,
  doNotStore?: boolean // if true, do not save the object into the connector store
}

IConnector:createSuppliedProduct(parameters): ISuppliedProduct

parameters: {
  other: ISuppliedProduct, // construct the object by copy 
  doNotStore?: boolean // if true, do not save the object into the connector store
}

Examples

Transformation loop

This example shows how to create a product case containing 10 pieces:

const connector = new Connector();
await connector.loadMeasures(JSON.stringify(measures));
await connector.loadVocabulary(JSON.stringify(vocabulary));

const piece = connector.MEASURES.UNIT.QUANTITYUNIT.PIECE;

const inputSuppliedProduct = connector.createSuppliedProduct({
    semanticId: "http://myplatform.com/inputProduct",
    description: "Some product"
});

const outputSuppliedProduct = connector.createSuppliedProduct({
    semanticId: "http://myplatform.com/caseOfProduct",
    description: "Case of 10 products"
});

const plannedConsumptionFlow = connector.createPlannedConsumptionFlow({
    semanticId: "http://myplatform.com/plannedConsumptionFlow",
    quantity: connector.createQuantity({ 
        value: 10, 
        unit: piece
    }),
    product: inputSuppliedProduct
})

const plannedProductionFlow = connector.createPlannedProductionFlow({
    semanticId: "http://myplatform.com/plannedProductionFlow",
    quantity: connector.createQuantity({ 
        value: 1.0, 
        unit: piece
    }),
    product: outputSuppliedProduct
})

const plannedTransformation = connector.createPlannedTransformation({
    semanticId: "http://myplatform.com/transformation",
    transformationType: connector.VOCABULARY.TRANSFORMATIONTYPE.COMBINES,
    consumptionFlows: [plannedConsumptionFlow],
    productionFlows: [plannedProductionFlow]
});