feat: add simple operation handlers

This commit is contained in:
Joachim Van Herwegen
2020-06-23 10:18:46 +02:00
parent 12fd00e3b8
commit fe8749390c
6 changed files with 147 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
import { Operation } from './Operation';
import { OperationHandler } from './OperationHandler';
import { ResourceStore } from '../../storage/ResourceStore';
import { ResponseDescription } from './ResponseDescription';
import { UnsupportedHttpError } from '../../util/errors/UnsupportedHttpError';
export class SimpleDeleteOperationHandler extends OperationHandler {
private readonly store: ResourceStore;
public constructor(store: ResourceStore) {
super();
this.store = store;
}
public async canHandle(input: Operation): Promise<void> {
if (input.method !== 'DELETE') {
throw new UnsupportedHttpError('This handler only supports DELETE operations.');
}
}
public async handle(input: Operation): Promise<ResponseDescription> {
await this.store.deleteResource(input.target);
return { identifier: input.target };
}
}

View File

@@ -0,0 +1,25 @@
import { Operation } from './Operation';
import { OperationHandler } from './OperationHandler';
import { ResourceStore } from '../../storage/ResourceStore';
import { ResponseDescription } from './ResponseDescription';
import { UnsupportedHttpError } from '../../util/errors/UnsupportedHttpError';
export class SimpleGetOperationHandler extends OperationHandler {
private readonly store: ResourceStore;
public constructor(store: ResourceStore) {
super();
this.store = store;
}
public async canHandle(input: Operation): Promise<void> {
if (input.method !== 'GET') {
throw new UnsupportedHttpError('This handler only supports GET operations.');
}
}
public async handle(input: Operation): Promise<ResponseDescription> {
const body = await this.store.getRepresentation(input.target, input.preferences);
return { identifier: input.target, body };
}
}

View File

@@ -0,0 +1,28 @@
import { Operation } from './Operation';
import { OperationHandler } from './OperationHandler';
import { ResourceStore } from '../../storage/ResourceStore';
import { ResponseDescription } from './ResponseDescription';
import { UnsupportedHttpError } from '../../util/errors/UnsupportedHttpError';
export class SimplePostOperationHandler extends OperationHandler {
private readonly store: ResourceStore;
public constructor(store: ResourceStore) {
super();
this.store = store;
}
public async canHandle(input: Operation): Promise<void> {
if (input.method !== 'POST') {
throw new UnsupportedHttpError('This handler only supports POST operations.');
}
if (!input.body) {
throw new UnsupportedHttpError('POST operations require a body.');
}
}
public async handle(input: Operation): Promise<ResponseDescription> {
const identifier = await this.store.addResource(input.target, input.body);
return { identifier };
}
}