Skip to content

Commit

Permalink
feat: add support for embedded jsonld (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
skynet2 authored Nov 20, 2024
1 parent bb3317b commit 6fbb610
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
25 changes: 19 additions & 6 deletions doc/ld/documentloader/document_loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package documentloader
import (
"errors"
"fmt"
"strings"

jsonld "github.com/piprate/json-gold/ld"

Expand Down Expand Up @@ -109,17 +110,29 @@ func (l *DocumentLoader) LoadDocument(u string) (*jsonld.RemoteDocument, error)
return nil, fmt.Errorf("load document: %w", err)
}

if l.remoteDocumentLoader == nil { // fetching from the remote URL is disabled
return nil, ErrContextNotFound
}

return l.loadDocumentFromURL(u)
return l.loadRemoteDocument(u)
}

return rd, nil
}

func (l *DocumentLoader) loadDocumentFromURL(u string) (*jsonld.RemoteDocument, error) {
func (l *DocumentLoader) loadRemoteDocument(u string) (*jsonld.RemoteDocument, error) {
if !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") {
doc, err := jsonld.DocumentFromReader(strings.NewReader(u))
if err != nil {
return nil, fmt.Errorf("parse document from reader: %w", err)
}

return &jsonld.RemoteDocument{
DocumentURL: u,
Document: doc,
}, nil
}

if l.remoteDocumentLoader == nil { // fetching from the remote URL is disabled
return nil, ErrContextNotFound
}

rd, err := l.remoteDocumentLoader.LoadDocument(u)
if err != nil {
return nil, fmt.Errorf("load remote context document: %w", err)
Expand Down
27 changes: 27 additions & 0 deletions doc/ld/documentloader/document_loader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,33 @@ func TestLoadDocument(t *testing.T) {
require.NoError(t, err)
})

t.Run("Load embedded document", func(t *testing.T) {
store := mockldstore.NewMockContextStore()
loader, err := documentloader.NewDocumentLoader(createMockProvider(withContextStore(store)))
require.NotNil(t, loader)
require.NoError(t, err)

rd, err := loader.LoadDocument(sampleJSONLDContext)

require.NotNil(t, rd)
require.NoError(t, err)

require.EqualValues(t, sampleJSONLDContext, rd.DocumentURL)
require.NotNil(t, rd.Document)
})

t.Run("Load embedded document fail", func(t *testing.T) {
store := mockldstore.NewMockContextStore()
loader, err := documentloader.NewDocumentLoader(createMockProvider(withContextStore(store)))
require.NotNil(t, loader)
require.NoError(t, err)

rd, err := loader.LoadDocument(`{...}`)

require.ErrorContains(t, err, "parse document from reader")
require.Nil(t, rd)
})

t.Run("Fetch remote context document and import into store", func(t *testing.T) {
store := mockldstore.NewMockContextStore()
store.Store.ErrGet = storage.ErrDataNotFound
Expand Down

0 comments on commit 6fbb610

Please sign in to comment.