Skip to content

Commit

Permalink
feat: Add Content-Type constructor to metadata.
Browse files Browse the repository at this point in the history
  • Loading branch information
RubenVerborgh committed Jan 11, 2021
1 parent 775aaa7 commit be1af89
Show file tree
Hide file tree
Showing 18 changed files with 67 additions and 47 deletions.
3 changes: 1 addition & 2 deletions src/init/AclInitializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { TEXT_TURTLE } from '../util/ContentTypes';
import { NotFoundHttpError } from '../util/errors/NotFoundHttpError';
import { ensureTrailingSlash } from '../util/PathUtil';
import { guardedStreamFrom } from '../util/StreamUtil';
import { CONTENT_TYPE } from '../util/Vocabularies';
import { Initializer } from './Initializer';

/**
Expand Down Expand Up @@ -67,7 +66,7 @@ export class AclInitializer extends Initializer {
acl:mode acl:Control;
acl:accessTo <${this.baseUrl}>;
acl:default <${this.baseUrl}>.`;
const metadata = new RepresentationMetadata(rootAcl, { [CONTENT_TYPE]: TEXT_TURTLE });
const metadata = new RepresentationMetadata(rootAcl, TEXT_TURTLE);
this.logger.debug(`Installing root ACL document at ${rootAcl.path}`);
await this.store.setRepresentation(
rootAcl,
Expand Down
39 changes: 30 additions & 9 deletions src/ldp/representation/RepresentationMetadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import { DataFactory, Store } from 'n3';
import type { BlankNode, Literal, NamedNode, Quad, Term } from 'rdf-js';
import { getLoggerFor } from '../../logging/LogUtil';
import { toSubjectTerm, toObjectTerm, toCachedNamedNode, isTerm } from '../../util/TermUtil';
import { CONTENT_TYPE_TERM } from '../../util/Vocabularies';
import { CONTENT_TYPE, CONTENT_TYPE_TERM } from '../../util/Vocabularies';
import type { ResourceIdentifier } from './ResourceIdentifier';
import { isResourceIdentifier } from './ResourceIdentifier';

export type MetadataIdentifier = ResourceIdentifier | NamedNode | BlankNode;
export type MetadataOverrideValue = NamedNode | Literal | string | (NamedNode | Literal | string)[];
export type MetadataValue = NamedNode | Literal | string | (NamedNode | Literal | string)[];
export type MetadataRecord = Record<string, MetadataValue>;

/**
* Determines whether the object is a `RepresentationMetadata`.
Expand All @@ -34,23 +35,40 @@ export class RepresentationMetadata {
*
* `@ignored` tag is necessary for Components-Generator.js
*/
public constructor(identifier?: MetadataIdentifier, overrides?: Record<string, MetadataOverrideValue>);
public constructor(identifier?: MetadataIdentifier, overrides?: MetadataRecord);

/**
* @param metadata - Starts as a copy of the input metadata.
* @param overrides - Key/value map of extra values that need to be added to the metadata.
* Will override values that were set by the input metadata.
*/
public constructor(metadata?: RepresentationMetadata, overrides?: Record<string, MetadataOverrideValue>);
public constructor(metadata?: RepresentationMetadata, overrides?: MetadataRecord);

/**
* @param overrides - Key/value map of extra values that need to be added to the metadata.
* @param identifier - Identifier of the resource relevant to this metadata.
* @param contentType - Override for the content type of the representation.
*/
public constructor(overrides?: Record<string, MetadataOverrideValue>);
public constructor(identifier?: MetadataIdentifier, contentType?: string);

/**
* @param metadata - Starts as a copy of the input metadata.
* @param contentType - Override for the content type of the representation.
*/
public constructor(metadata?: RepresentationMetadata, contentType?: string);

/**
* @param contentType - The content type of the representation.
*/
public constructor(contentType?: string);

/**
* @param overrides - Metadata values (defaulting to content type if a string)
*/
public constructor(metadata?: RepresentationMetadata | MetadataRecord | string);

public constructor(
input?: MetadataIdentifier | RepresentationMetadata | Record<string, MetadataOverrideValue>,
overrides?: Record<string, MetadataOverrideValue>,
input?: MetadataIdentifier | RepresentationMetadata | MetadataRecord | string,
overrides?: MetadataRecord | string,
) {
this.store = new Store();
if (isResourceIdentifier(input)) {
Expand All @@ -66,11 +84,14 @@ export class RepresentationMetadata {
}

if (overrides) {
if (typeof overrides === 'string') {
overrides = { [CONTENT_TYPE]: overrides };
}
this.setOverrides(overrides);
}
}

private setOverrides(overrides: Record<string, MetadataOverrideValue>): void {
private setOverrides(overrides: Record<string, MetadataValue>): void {
for (const predicate of Object.keys(overrides)) {
const namedPredicate = toCachedNamedNode(predicate);
this.removeAll(namedPredicate);
Expand Down
3 changes: 1 addition & 2 deletions src/storage/conversion/ContentTypeReplacer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { Representation } from '../../ldp/representation/Representation';
import { RepresentationMetadata } from '../../ldp/representation/RepresentationMetadata';
import type { ValuePreferences } from '../../ldp/representation/RepresentationPreferences';
import { NotImplementedHttpError } from '../../util/errors/NotImplementedHttpError';
import { CONTENT_TYPE } from '../../util/Vocabularies';
import { matchesMediaType, matchingMediaTypes } from './ConversionUtil';
import type { RepresentationConverterArgs } from './RepresentationConverter';
import { RepresentationConverter } from './RepresentationConverter';
Expand Down Expand Up @@ -50,7 +49,7 @@ export class ContentTypeReplacer extends RepresentationConverter {
*/
public async handle({ representation, preferences }: RepresentationConverterArgs): Promise<Representation> {
const contentType = this.getReplacementType(representation.metadata.contentType, preferences.type);
const metadata = new RepresentationMetadata(representation.metadata, { [CONTENT_TYPE]: contentType });
const metadata = new RepresentationMetadata(representation.metadata, contentType);
return { ...representation, metadata };
}

Expand Down
4 changes: 2 additions & 2 deletions src/storage/conversion/QuadToRdfConverter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { ValuePreferences } from '../../ldp/representation/RepresentationPr
import { INTERNAL_QUADS } from '../../util/ContentTypes';
import { guardStream } from '../../util/GuardedStream';
import { pipeSafely } from '../../util/StreamUtil';
import { CONTENT_TYPE, PREFERRED_PREFIX_TERM } from '../../util/Vocabularies';
import { PREFERRED_PREFIX_TERM } from '../../util/Vocabularies';
import { matchingMediaTypes } from './ConversionUtil';
import type { RepresentationConverterArgs } from './RepresentationConverter';
import { TypedRepresentationConverter } from './TypedRepresentationConverter';
Expand All @@ -27,7 +27,7 @@ export class QuadToRdfConverter extends TypedRepresentationConverter {

public async handle({ representation: quads, preferences }: RepresentationConverterArgs): Promise<Representation> {
const contentType = matchingMediaTypes(preferences.type, await this.getOutputTypes())[0];
const metadata = new RepresentationMetadata(quads.metadata, { [CONTENT_TYPE]: contentType });
const metadata = new RepresentationMetadata(quads.metadata, contentType);
let data: Readable;

// Use prefixes if possible (see https://github.com/rubensworks/rdf-serialize.js/issues/1)
Expand Down
3 changes: 1 addition & 2 deletions src/storage/conversion/RdfToQuadConverter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { RepresentationMetadata } from '../../ldp/representation/RepresentationM
import { INTERNAL_QUADS } from '../../util/ContentTypes';
import { BadRequestHttpError } from '../../util/errors/BadRequestHttpError';
import { pipeSafely } from '../../util/StreamUtil';
import { CONTENT_TYPE } from '../../util/Vocabularies';
import type { RepresentationConverterArgs } from './RepresentationConverter';
import { TypedRepresentationConverter } from './TypedRepresentationConverter';

Expand All @@ -18,7 +17,7 @@ export class RdfToQuadConverter extends TypedRepresentationConverter {
}

public async handle({ representation, identifier }: RepresentationConverterArgs): Promise<Representation> {
const metadata = new RepresentationMetadata(representation.metadata, { [CONTENT_TYPE]: INTERNAL_QUADS });
const metadata = new RepresentationMetadata(representation.metadata, INTERNAL_QUADS);
const rawQuads = rdfParser.parse(representation.data, {
contentType: representation.metadata.contentType!,
baseIRI: identifier.path,
Expand Down
3 changes: 1 addition & 2 deletions src/storage/patch/SparqlUpdatePatchHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { NotFoundHttpError } from '../../util/errors/NotFoundHttpError';
import { NotImplementedHttpError } from '../../util/errors/NotImplementedHttpError';
import { guardStream } from '../../util/GuardedStream';
import type { ResourceLocker } from '../../util/locking/ResourceLocker';
import { CONTENT_TYPE } from '../../util/Vocabularies';
import type { ResourceStore } from '../ResourceStore';
import { PatchHandler } from './PatchHandler';

Expand Down Expand Up @@ -109,7 +108,7 @@ export class SparqlUpdatePatchHandler extends PatchHandler {
this.logger.debug(`${store.size} quads will be stored to ${identifier.path}.`);

// Write the result
const metadata = new RepresentationMetadata(identifier, { [CONTENT_TYPE]: INTERNAL_QUADS });
const metadata = new RepresentationMetadata(identifier, INTERNAL_QUADS);
const representation: Representation = {
binary: false,
data: guardStream(store.match() as Readable),
Expand Down
7 changes: 2 additions & 5 deletions test/integration/LdpHandlerWithAuth.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { createReadStream } from 'fs';
import type { HttpHandler, Initializer, ResourceStore } from '../../src/';
import {
CONTENT_TYPE, LDP,
RepresentationMetadata, guardStream, joinFilePath,
} from '../../src/';
import { LDP, RepresentationMetadata, guardStream, joinFilePath } from '../../src/';
import { AclHelper, ResourceHelper } from '../util/TestHelpers';
import { BASE, getTestFolder, createFolder, removeFolder, instantiateFromConfig } from './Config';

Expand Down Expand Up @@ -59,7 +56,7 @@ describe.each(stores)('An LDP handler with auth using %s', (name, { storeUrn, se
await store.setRepresentation({ path: `${BASE}/permanent.txt` }, {
binary: true,
data: guardStream(createReadStream(joinFilePath(__dirname, '../assets/permanent.txt'))),
metadata: new RepresentationMetadata({ [CONTENT_TYPE]: 'text/plain' }),
metadata: new RepresentationMetadata('text/plain'),
});
});

Expand Down
3 changes: 1 addition & 2 deletions test/integration/LockingResourceStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import type { ResourceLocker } from '../../src/util/locking/ResourceLocker';
import { SingleThreadedResourceLocker } from '../../src/util/locking/SingleThreadedResourceLocker';
import { WrappedExpiringResourceLocker } from '../../src/util/locking/WrappedExpiringResourceLocker';
import { guardedStreamFrom } from '../../src/util/StreamUtil';
import { CONTENT_TYPE } from '../../src/util/Vocabularies';
import { BASE } from './Config';

describe('A LockingResourceStore', (): void => {
Expand All @@ -40,7 +39,7 @@ describe('A LockingResourceStore', (): void => {
store = new LockingResourceStore(source, expiringLocker);

// Make sure something is in the store before we read from it in our tests.
const metadata = new RepresentationMetadata({ [CONTENT_TYPE]: APPLICATION_OCTET_STREAM });
const metadata = new RepresentationMetadata(APPLICATION_OCTET_STREAM);
const data = guardedStreamFrom([ 1, 2, 3 ]);
await store.setRepresentation({ path }, { metadata, data, binary: true });
});
Expand Down
5 changes: 2 additions & 3 deletions test/integration/RepresentationConverter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { ChainedConverter } from '../../src/storage/conversion/ChainedConverter'
import { QuadToRdfConverter } from '../../src/storage/conversion/QuadToRdfConverter';
import { RdfToQuadConverter } from '../../src/storage/conversion/RdfToQuadConverter';
import { guardedStreamFrom, readableToString } from '../../src/util/StreamUtil';
import { CONTENT_TYPE } from '../../src/util/Vocabularies';

describe('A ChainedConverter', (): void => {
const converters = [
Expand All @@ -14,7 +13,7 @@ describe('A ChainedConverter', (): void => {
const converter = new ChainedConverter(converters);

it('can convert from JSON-LD to turtle.', async(): Promise<void> => {
const metadata = new RepresentationMetadata({ [CONTENT_TYPE]: 'application/ld+json' });
const metadata = new RepresentationMetadata('application/ld+json');
const representation: Representation = {
binary: true,
data: guardedStreamFrom(
Expand All @@ -34,7 +33,7 @@ describe('A ChainedConverter', (): void => {
});

it('can convert from turtle to JSON-LD.', async(): Promise<void> => {
const metadata = new RepresentationMetadata({ [CONTENT_TYPE]: 'text/turtle' });
const metadata = new RepresentationMetadata('text/turtle');
const representation: Representation = {
binary: true,
data: guardedStreamFrom([ '<http://test.com/s> <http://test.com/p> <http://test.com/o>.' ]),
Expand Down
3 changes: 1 addition & 2 deletions test/unit/ldp/http/BasicResponseWriter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { RepresentationMetadata } from '../../../../src/ldp/representation/Repre
import { INTERNAL_QUADS } from '../../../../src/util/ContentTypes';
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';
import { guardedStreamFrom } from '../../../../src/util/StreamUtil';
import { CONTENT_TYPE } from '../../../../src/util/Vocabularies';
import { StaticAsyncHandler } from '../../../util/StaticAsyncHandler';

describe('A BasicResponseWriter', (): void => {
Expand All @@ -28,7 +27,7 @@ describe('A BasicResponseWriter', (): void => {
it('requires the input to be a binary ResponseDescription.', async(): Promise<void> => {
await expect(writer.canHandle({ response, result: new Error('error') }))
.rejects.toThrow(NotImplementedHttpError);
const metadata = new RepresentationMetadata({ [CONTENT_TYPE]: INTERNAL_QUADS });
const metadata = new RepresentationMetadata(INTERNAL_QUADS);
await expect(writer.canHandle({ response, result: { statusCode: 201, metadata }}))
.rejects.toThrow(NotImplementedHttpError);
await expect(writer.canHandle({ response, result }))
Expand Down
13 changes: 12 additions & 1 deletion test/unit/ldp/representation/RepresentationMetadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,22 @@ describe('A RepresentationMetadata', (): void => {
expect(metadata.identifier).toEqualRdfTerm(namedNode('identifier'));
});

it('converts identifier strings to named nodes.', async(): Promise<void> => {
it('converts identifiers to named nodes.', async(): Promise<void> => {
metadata = new RepresentationMetadata({ path: 'identifier' });
expect(metadata.identifier).toEqualRdfTerm(namedNode('identifier'));
});

it('converts string to content type.', async(): Promise<void> => {
metadata = new RepresentationMetadata('text/turtle');
expect(metadata.contentType).toEqual('text/turtle');

metadata = new RepresentationMetadata({ path: 'identifier' }, 'text/turtle');
expect(metadata.contentType).toEqual('text/turtle');

metadata = new RepresentationMetadata(new RepresentationMetadata(), 'text/turtle');
expect(metadata.contentType).toEqual('text/turtle');
});

it('copies an other metadata object.', async(): Promise<void> => {
const other = new RepresentationMetadata({ path: 'otherId' }, { 'test:pred': 'objVal' });
metadata = new RepresentationMetadata(other);
Expand Down
2 changes: 1 addition & 1 deletion test/unit/storage/RepresentationConvertingStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('A RepresentationConvertingStore', (): void => {
const convertedIn = { metadata: {}};
const convertedOut = { metadata: {}};
const inType = 'text/turtle';
const metadata = new RepresentationMetadata({ [CONTENT_TYPE]: 'text/turtle' });
const metadata = new RepresentationMetadata('text/turtle');
let representation: Representation;

beforeEach(async(): Promise<void> => {
Expand Down
2 changes: 1 addition & 1 deletion test/unit/storage/accessors/FileDataAccessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('A FileDataAccessor', (): void => {
cache = mockFs(rootFilePath, now);
accessor = new FileDataAccessor(new ExtensionBasedMapper(base, rootFilePath));

metadata = new RepresentationMetadata({ [CONTENT_TYPE]: APPLICATION_OCTET_STREAM });
metadata = new RepresentationMetadata(APPLICATION_OCTET_STREAM);

data = guardedStreamFrom([ 'data' ]);
});
Expand Down
4 changes: 2 additions & 2 deletions test/unit/storage/accessors/InMemoryDataAccessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { APPLICATION_OCTET_STREAM } from '../../../../src/util/ContentTypes';
import { NotFoundHttpError } from '../../../../src/util/errors/NotFoundHttpError';
import type { Guarded } from '../../../../src/util/GuardedStream';
import { guardedStreamFrom, readableToString } from '../../../../src/util/StreamUtil';
import { CONTENT_TYPE, LDP, RDF } from '../../../../src/util/Vocabularies';
import { LDP, RDF } from '../../../../src/util/Vocabularies';

describe('An InMemoryDataAccessor', (): void => {
const base = 'http://test.com/';
Expand All @@ -21,7 +21,7 @@ describe('An InMemoryDataAccessor', (): void => {
// Create default root container
await accessor.writeContainer({ path: `${base}` }, new RepresentationMetadata());

metadata = new RepresentationMetadata({ [CONTENT_TYPE]: APPLICATION_OCTET_STREAM });
metadata = new RepresentationMetadata(APPLICATION_OCTET_STREAM);

data = guardedStreamFrom([ 'data' ]);
});
Expand Down
2 changes: 1 addition & 1 deletion test/unit/storage/conversion/ChainedConverter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ describe('A ChainedConverter', (): void => {
];
converter = new ChainedConverter(converters);

const metadata = new RepresentationMetadata({ [CONTENT_TYPE]: 'text/turtle' });
const metadata = new RepresentationMetadata('text/turtle');
representation = { metadata } as Representation;
preferences = { type: { 'internal/quads': 1 }};
args = { representation, preferences, identifier: { path: 'path' }};
Expand Down
4 changes: 2 additions & 2 deletions test/unit/storage/conversion/QuadToRdfConverter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ import type { RepresentationPreferences } from '../../../../src/ldp/representati
import type { ResourceIdentifier } from '../../../../src/ldp/representation/ResourceIdentifier';
import { QuadToRdfConverter } from '../../../../src/storage/conversion/QuadToRdfConverter';
import { INTERNAL_QUADS } from '../../../../src/util/ContentTypes';
import { CONTENT_TYPE, DC, PREFERRED_PREFIX_TERM } from '../../../../src/util/Vocabularies';
import { DC, PREFERRED_PREFIX_TERM } from '../../../../src/util/Vocabularies';

describe('A QuadToRdfConverter', (): void => {
const converter = new QuadToRdfConverter();
const identifier: ResourceIdentifier = { path: 'path' };
let metadata: RepresentationMetadata;

beforeEach((): void => {
metadata = new RepresentationMetadata({ [CONTENT_TYPE]: INTERNAL_QUADS });
metadata = new RepresentationMetadata(INTERNAL_QUADS);
});

it('supports parsing quads.', async(): Promise<void> => {
Expand Down
Loading

0 comments on commit be1af89

Please sign in to comment.