npm i cocoda-sdkWe also provide a browser bundle https://cdn.jsdelivr.net/npm/cocoda-sdk@2/dist/cocoda-sdk.js
cocoda-sdk exports a default instance, so the same object is used on each import of cocoda-sdk. We recommend using this instance over creating one's own.
const { cdk } = require("cocoda-sdk") // CommonJS
import { cdk } from "cocoda-sdk" // ESMSince cocoda-sdk is an ES module, we'll use the import/export syntax in the rest of the documentation.
cocoda-sdk also exports some other members:
CocodaSDK- the class that is behind the default instanceerrors- see Errorsproviders- an object with all provider classes- All individual provider classes - see Providers
- Note: You need to append
Providerto the names, e.g.LocalMappingsis exported asLocalMappingsProvider.
- Note: You need to append
addAllProviders- a method that adds all avaiable providers to an instance- Can be called without parameters to add to the default instance. Useful if you need all providers.
cocoda-sdk can be configured after import:
import { cdk } from "cocoda-sdk"
cdk.setConfig(config)The configuration can also be loaded from a URL:
import { cdk } from "cocoda-sdk"
await cdk.loadConfig("https://raw.githubusercontent.com/gbv/cocoda/dev/config/cocoda.default.json")The configuration is a JSON object corresponding the the configuration format of Cocoda. In particular, the configuration contains an array property registries.
If you only use cocoda-sdk with a single registry, configuration might not be necessary (see below).
A registry is an individual source of data, for instance a set of concept schemes available from a specific terminology service. The simplest registry consists only of a unique identifier (uri) and the name of the access provider (provider):
{
"uri": "http://coli-conc.gbv.de/registry/local-mappings",
"provider": "LocalMappings"
}For most providers the configuration should use the BARTOC vocabulary API type URI instead:
{
"api": "http://bartoc.org/api-type/skosmos",
"endpoint": "https://www.loterre.fr/skosmos/905/"
}A list of available providers can be found below. Most providers need additional properties to work correctly.
For many providers, you need to specify one or more endpoints on the registry object for it to work. There are, however, three steps in which these endpoints are determined:
- By explicitly specifying an endpoint on the registry object.
- By performaning a request to the provider's
/statusendpoint and parsing its result (which is done inregistry.init()). - By implication using the
apibase URL.
Values set earlier in these steps will never be overwritten by later steps. That means to disable an endpoint explicitly, you can set it to null when configuring the registry. Also, if step 2 is successful, it will be assumed that no further endpoints exist and all missing endpoints will be set to null, i.e. essentially skipping step 3.
If you only have a single registry you want to access, you can initialize it as follows:
import { cdk, LocalMappingsProvider } from "cocoda-sdk"
// Local mappings are not included by default
cdk.addProvider(LocalMappingsProvider)
const registry = cdk.initializeRegistry({
uri: "http://coli-conc.gbv.de/registry/local-mappings",
provider: "LocalMappings"
})
// Now, access methods are available on the registry:
registry.getMappings()Most Providers can also be initialized with API Type URI from BARTOC vocabulary API types list:
const registry = cdk.initializeRegistry({
api: "http://bartoc.org/api-type/skosmos",
endpoint: "https://www.loterre.fr/skosmos/905/"
})It's also possible to directly use Registry classes.
If you initialize cocoda-sdk with a configuration, it will initialize all included registries automatically. Those registries are then accessible via cdk.config.registries. Alternatively, you can retrieve registries by URI:
// After setting up cdk
const registry = cdk.getRegistryForUri("...")Providers allow access to different types of APIs.
The following providers are offered in cocoda-sdk by default:
Base- the base provider that all other providers have to inherit fromConceptApi- access to concept schemes and concepts via JSKOS API (jskos-server and compatible implementations)MappingsApi- access to concordances, mappings, and annotations via jskos-server
The following providers are also exported, but have to be added via cdk.addProvider:
LocalMappings- access to local mappings via localForage (only available in browser)SkosmosApi- access to concept schemes and concepts via a Skosmos APIOlsApi- access to ontologies via Ontology Lookup Service (OLS) API Version 2 (experimental)LocApi- access to concept schemes and concepts via the Library of Congress Linked Data Service- This integration is currently experimental and only supports LCSH and LCNAF.
Skohub- access to concept schemes and concepts via a SkoHub Vocabs- This integration is currently experimental. Only vocabularies that use a slash namespace pattern with dereferenceable URIs are supported.
LobidApi- access to GND via lobid- This integration is currently experimental.
MyCoRe- access to vocabularies via MyCoRe- This integration is currently experimental. Only one vocabulary per registry is supported. Not recommended for large vocabularies as all of the vocabulary data is loaded and kept in memory.
ReconciliationApi- access to mapping suggestions via a Reconciliation Service APIOccurrencesApi- access to concept occurrences via occurrences-api (will be changed to occurrences-server in the future)LabelSearchSuggestion- access to mapping suggestions using other registries' search endpoints (using jskos-server)ModApi- (experimental) access to concept schemes and concepts via a MOD API
To add a provider, append Provider to its name and import it together with cdk:
import { cdk, LocApiProvider } from "cocoda-sdk"
cdk.addProvider(LocApiProvider)Note that in the browser bundle, all providers listed above are included and do not have to be added separately.
Please refer to each provider's documentation for how exactly to configure that provider: Documentation
It is also possible to add custom providers that inherit from BaseProvider:
import { cdk, BaseProvider } from "cocoda-sdk"
export class CustomProvider extends BaseProvider {
static providerName = "Dummy"
// static providerType = "..." // Optional URI from https://bartoc.org/api-type/
getConcepts() {
return [
{ prefLabel: { en: "Hello!" } },
]
}
}
cdk.addProvider(CustomProvider)See examples/custom-provider.js for an extended example.
The createInstance method can be used to create a new and independent instance with a separate configuration if needed:
const newCdk = cdk.createInstance(config)The following is a barebones example on how to use cocoda-sdk together with login-client.
Prerequisites:
- A local instance of Login Server running on
localhost:3004- Needs a configured identity provider with at least one user
- The HTTP server that is serving the example below must be configured under
ALLOWED_ORIGINS - The user must already be logged in
- A local instance of JSKOS Server running on
localhost:3000- The Login Server's public key must be configured
- Mappings must be enabled for authenticated users (is given for the default configuration)
See also the code comments inside the example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<!-- login-client, cocoda-sdk -->
<script src="https://cdn.jsdelivr.net/npm/gbv-login-client@0"></script>
<script src="https://cdn.jsdelivr.net/npm/cocoda-sdk@2"></script>
<script>
// Initialize mapping registry at localhost:3000
const registry = CDK.cdk.initializeRegistry({
provider: "MappingsApi",
uri: "local:mappings",
status: "http://localhost:3000/status",
})
// Note: This is an async function, so we might be dealing with race conditions here.
registry.init()
// Create client to connect to Login Server at localhost:3004
let client = new LoginClient("localhost:3004", { ssl: false })
let user
// Add listener for all event types
client.addEventListener(null, event => {
switch (event.type) {
case LoginClient.events.connect:
// At this point, we don't know whether the user has logged in yet, but we can try
console.log(registry.isAuthorizedFor({ type: "mappings", action: "create", user }))
break
case LoginClient.events.login:
// Update user
user = event.user
// Now we know the user is logged in, so this should return true
// Note that if the user is already logged in, this event will fire before connected
console.log(registry.isAuthorizedFor({ type: "mappings", action: "create", user }))
break
case LoginClient.events.update:
// Update user
user = event.user
break
case LoginClient.events.about:
// Register the server's public key in the registry
registry.setAuth({ key: event.publicKey })
break
case LoginClient.events.token:
// On every token update, update the token in the registry
registry.setAuth({ bearerToken: event.token })
break
}
})
// Start connection to client
client.connect()
</script>
</body>
</html>Note that for a real application, there are more things necessary:
- Track whether the client is connected and whether the user is logged in
- Tell the user to log in if necessary
- Check if the
registry.init()call finished before making requests (might not be necessary because requests will wait for initialization) - Error handling
- etc.
You can find more in-depth examples here:
- The Vuex store module for authentication in Cocoda.
- Even if you're not using Vue.js, this can be helpful.
- Cocoda is using cocoda-sdk extensively, so other parts of the code might also be helpful. It has gotten pretty big and complex though.
- The API page of Login Server. This is merely an example on how to use
login-client.
A cocoda-sdk instance itself offers only a handful of methods. The actual access to APIs happens through registries. The following list of methods assume either an instance of cocoda-sdk (cdk.someMethod) or an initialized registry (registry.someMethod). Documentation for registry methods is on a per-provider basis. While the API should be the same for a particular methods across providers, the details on how to use it might differ.
Please refer to the documentation for a list of methods of for cocoda-sdk instances.
-
supportsScheme. Implemented by: -
setAuth- Implemented by BaseProvider
-
setRetryConfig
- Implemented by BaseProvider
-
getCancelTokenSource
- Implemented by BaseProvider
-
getSchemes -
vocSearch -
vocSuggest
- MappingsApiProvider - getMappings
- LocalMappingsProvider - getMappings
- ReconciliationApiProvider - getMappings
- LabelSearchSuggestionProvider - getMappings
- OccurrencesApiProvider - getMappings
getTypes({ scheme }) returns a list of types for some concept scheme(s). Implemented by:
cocoda-sdk defines some custom errors, grouped in exporteable object errors:
import { errors } from "cocoda-sdk"The following errors are defined:
CDKError- generic errorMethodNotImplementedError- called method is available, but not implemented by the providerInvalidOrMissingParameterError- a parameter is missing or invalidBackendError- a response was received, but there was a problem on the backendBackendUnavailableError- no response was received, but the client's internet connection seems to be workingNetworkError- there was a problem with the networkInvalidRequestError- the request was invalidMissingApiUrlError- the API URL necessary to make this request is not defined on the registry
For details about the errors, refer to the documentation.
See CONTRIBUTING.md
MIT Copyright (c) 2021- Verbundzentrale des GBV (VZG)