Skip to content

Commit

Permalink
Merge pull request #8 from event-catalog/refactored-sdk-to-resources
Browse files Browse the repository at this point in the history
chore(sdk): refactored code to new resource internal lib
  • Loading branch information
boyney123 authored Jul 18, 2024
2 parents 51d5d78 + 6eee370 commit 8550962
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 157 deletions.
5 changes: 5 additions & 0 deletions .changeset/shiny-bottles-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@eventcatalog/sdk": patch
---

chore(sdk): refactored code to new resource internal lib
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.0.4",
"description": "SDK to integrate with EventCatalog",
"scripts": {
"build": "tsup ./src",
"build": "tsup",
"test": "vitest",
"format": "prettier --write .",
"format:diff": "prettier --list-different .",
Expand Down
87 changes: 10 additions & 77 deletions src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { join } from 'node:path';
import { dirname } from 'node:path';
import { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './internal/utils';
import type { Event } from './types';
import { addFileToResource, getResource, rmResourceById, versionResource, writeResource } from './internal/resources';

/**
* Returns an event from EventCatalog.
Expand All @@ -25,18 +26,8 @@ import type { Event } from './types';
*/
export const getEvent =
(directory: string) =>
async (id: string, version?: string): Promise<Event> => {
const file = await findFileById(directory, id, version);

if (!file) throw new Error(`No event found for the given id: ${id}` + (version ? ` and version ${version}` : ''));

const { data, content } = matter.read(file);

return {
...data,
markdown: content.trim(),
} as Event;
};
async (id: string, version?: string): Promise<Event> =>
getResource(directory, id, version, { type: 'event' }) as Promise<Event>;

/**
* Write an event to EventCatalog.
Expand Down Expand Up @@ -72,20 +63,8 @@ export const getEvent =
*/
export const writeEvent =
(directory: string) =>
async (event: Event, options: { path: string } = { path: '' }) => {
// Get the path
const path = options.path || `/${event.id}`;
const exists = await versionExists(directory, event.id, event.version);

if (exists) {
throw new Error(`Failed to write event as the version ${event.version} already exists`);
}

const { markdown, ...frontmatter } = event;
const document = matter.stringify(markdown.trim(), frontmatter);
await fs.mkdir(join(directory, path), { recursive: true });
await fs.writeFile(join(directory, path, 'index.md'), document);
};
async (event: Event, options: { path: string } = { path: '' }) =>
writeResource(directory, { ...event }, { ...options, type: 'event' });

/**
* Delete an event at it's given path.
Expand Down Expand Up @@ -123,18 +102,8 @@ export const rmEvent = (directory: string) => async (path: string) => {
* await rmEventById('InventoryAdjusted', '0.0.1');
* ```
*/
export const rmEventById = (directory: string) => async (id: string, version?: string) => {
// Find all the events in the directory
const files = await getFiles(`${directory}/**/index.md`);

const matchedFiles = await searchFilesForId(files, id, version);

if (matchedFiles.length === 0) {
throw new Error(`No event found with id: ${id}`);
}

await Promise.all(matchedFiles.map((file) => fs.rm(file)));
};
export const rmEventById = (directory: string) => async (id: string, version?: string) =>
rmResourceById(directory, id, version, { type: 'event' });

/**
* Version an event by it's id.
Expand All @@ -154,39 +123,7 @@ export const rmEventById = (directory: string) => async (id: string, version?: s
*
* ```
*/
export const versionEvent = (directory: string) => async (id: string) => {
// Find all the events in the directory
const files = await getFiles(`${directory}/**/index.md`);
const matchedFiles = await searchFilesForId(files, id);

if (matchedFiles.length === 0) {
throw new Error(`No event found with id: ${id}`);
}

// Event that is in the route of the project
const file = matchedFiles[0];
const eventDirectory = dirname(file);
const { data: { version = '0.0.1' } = {} } = matter.read(file);
const targetDirectory = join(eventDirectory, 'versioned', version);

await fs.mkdir(targetDirectory, { recursive: true });

// Copy the event to the versioned directory
await copyDir(directory, eventDirectory, targetDirectory, (src) => {
return !src.includes('versioned');
});

// Remove all the files in the root of the resource as they have now been versioned
await fs.readdir(eventDirectory).then(async (resourceFiles) => {
await Promise.all(
resourceFiles.map(async (file) => {
if (file !== 'versioned') {
await fs.rm(join(eventDirectory, file), { recursive: true });
}
})
);
});
};
export const versionEvent = (directory: string) => async (id: string) => versionResource(directory, id);

/**
* Add a file to an event by it's id.
Expand All @@ -208,12 +145,8 @@ export const versionEvent = (directory: string) => async (id: string) => {
* ```
*/
export const addFileToEvent =
(directory: string) => async (id: string, file: { content: string; fileName: string }, version?: string) => {
const pathToEvent = await findFileById(directory, id, version);
if (!pathToEvent) throw new Error('Cannot find directory to write file to');
const contentDirectory = dirname(pathToEvent);
await fs.writeFile(join(contentDirectory, file.fileName), file.content);
};
(directory: string) => async (id: string, file: { content: string; fileName: string }, version?: string) =>
addFileToResource(directory, id, file, version);

/**
* Add a schema to an event by it's id.
Expand Down
105 changes: 105 additions & 0 deletions src/internal/resources.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { dirname, join } from 'path';
import { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './utils';
import matter from 'gray-matter';
import fs from 'node:fs/promises';
import { Message, Service } from '../types';

type Resource = Service | Message;

export const versionResource = async (catalogDir: string, id: string) => {
// Find all the events in the directory
const files = await getFiles(`${catalogDir}/**/index.md`);
const matchedFiles = await searchFilesForId(files, id);

if (matchedFiles.length === 0) {
throw new Error(`No event found with id: ${id}`);
}

// Event that is in the route of the project
const file = matchedFiles[0];
const sourceDirectory = dirname(file);
const { data: { version = '0.0.1' } = {} } = matter.read(file);
const targetDirectory = join(sourceDirectory, 'versioned', version);

await fs.mkdir(targetDirectory, { recursive: true });

// Copy the event to the versioned directory
await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {
return !src.includes('versioned');
});

// Remove all the files in the root of the resource as they have now been versioned
await fs.readdir(sourceDirectory).then(async (resourceFiles) => {
await Promise.all(
resourceFiles.map(async (file) => {
if (file !== 'versioned') {
await fs.rm(join(sourceDirectory, file), { recursive: true });
}
})
);
});
};

export const writeResource = async (
catalogDir: string,
resource: Resource,
options: { path: string; type: string } = { path: '', type: '' }
) => {
// Get the path
const path = options.path || `/${resource.id}`;
const exists = await versionExists(catalogDir, resource.id, resource.version);

if (exists) {
throw new Error(`Failed to write ${options.type} as the version ${resource.version} already exists`);
}

const { markdown, ...frontmatter } = resource;
const document = matter.stringify(markdown.trim(), frontmatter);
await fs.mkdir(join(catalogDir, path), { recursive: true });
await fs.writeFile(join(catalogDir, path, 'index.md'), document);
};

export const getResource = async (
catalogDir: string,
id: string,
version?: string,
options?: { type: string }
): Promise<Resource> => {
const file = await findFileById(catalogDir, id, version);

if (!file)
throw new Error(
`No ${options?.type || 'resource'} found for the given id: ${id}` + (version ? ` and version ${version}` : '')
);

const { data, content } = matter.read(file);

return {
...data,
markdown: content.trim(),
} as Resource;
};

export const rmResourceById = async (catalogDir: string, id: string, version?: string, options?: { type: string }) => {
const files = await getFiles(`${catalogDir}/**/index.md`);
const matchedFiles = await searchFilesForId(files, id, version);

if (matchedFiles.length === 0) {
throw new Error(`No ${options?.type || 'resource'} found with id: ${id}`);
}

await Promise.all(matchedFiles.map((file) => fs.rm(file)));
};

export const addFileToResource = async (
catalogDir: string,
id: string,
file: { content: string; fileName: string },
version?: string
) => {
const pathToResource = await findFileById(catalogDir, id, version);

if (!pathToResource) throw new Error('Cannot find directory to write file to');

await fs.writeFile(join(dirname(pathToResource), file.fileName), file.content);
};
89 changes: 11 additions & 78 deletions src/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from
import type { Service } from './types';
import fs from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { addFileToResource, getResource, rmResourceById, versionResource, writeResource } from './internal/resources';

/**
* Returns a service from EventCatalog.
Expand All @@ -24,19 +25,8 @@ import { dirname, join } from 'node:path';
*/
export const getService =
(directory: string) =>
async (id: string, version?: string): Promise<Service> => {
const file = await findFileById(directory, id, version);

if (!file) throw new Error(`No service found for the given id: ${id}` + (version ? ` and version ${version}` : ''));

const { data, content } = matter.read(file);

return {
...data,
markdown: content.trim(),
} as Service;
};

async (id: string, version?: string): Promise<Service> =>
getResource(directory, id, version, { type: 'service' }) as Promise<Service>;
/**
* Write an event to EventCatalog.
*
Expand Down Expand Up @@ -71,20 +61,8 @@ export const getService =
*/
export const writeService =
(directory: string) =>
async (service: Service, options: { path: string } = { path: '' }) => {
// Get the path
const path = options.path || `/${service.id}`;
const exists = await versionExists(directory, service.id, service.version);

if (exists) {
throw new Error(`Failed to write service as the version ${service.version} already exists`);
}

const { markdown, ...frontmatter } = service;
const document = matter.stringify(markdown.trim(), frontmatter);
await fs.mkdir(join(directory, path), { recursive: true });
await fs.writeFile(join(directory, path, 'index.md'), document);
};
async (service: Service, options: { path: string } = { path: '' }) =>
writeResource(directory, { ...service }, { ...options, type: 'service' });

/**
* Version a service by it's id.
Expand All @@ -104,39 +82,7 @@ export const writeService =
*
* ```
*/
export const versionService = (directory: string) => async (id: string) => {
// Find all the events in the directory
const files = await getFiles(`${directory}/**/index.md`);
const matchedFiles = await searchFilesForId(files, id);

if (matchedFiles.length === 0) {
throw new Error(`No service found with id: ${id}`);
}

// Service that is in the route of the project
const file = matchedFiles[0];
const eventDirectory = dirname(file);
const { data: { version = '0.0.1' } = {} } = matter.read(file);
const targetDirectory = join(eventDirectory, 'versioned', version);

await fs.mkdir(targetDirectory, { recursive: true });

// Copy the service to the versioned directory
await copyDir(directory, eventDirectory, targetDirectory, (src) => {
return !src.includes('versioned');
});

// Remove all the files in the root of the resource as they have now been versioned
await fs.readdir(eventDirectory).then(async (resourceFiles) => {
await Promise.all(
resourceFiles.map(async (file) => {
if (file !== 'versioned') {
await fs.rm(join(eventDirectory, file), { recursive: true });
}
})
);
});
};
export const versionService = (directory: string) => async (id: string) => versionResource(directory, id);

/**
* Delete a service at it's given path.
Expand Down Expand Up @@ -173,18 +119,8 @@ export const rmService = (directory: string) => async (path: string) => {
* await rmServiceById('InventoryService', '0.0.1');
* ```
*/
export const rmServiceById = (directory: string) => async (id: string, version?: string) => {
// Find all the events in the directory
const files = await getFiles(`${directory}/**/index.md`);

const matchedFiles = await searchFilesForId(files, id, version);

if (matchedFiles.length === 0) {
throw new Error(`No service found with id: ${id}`);
}

await Promise.all(matchedFiles.map((file) => fs.rm(file)));
};
export const rmServiceById = (directory: string) => async (id: string, version?: string) =>
rmResourceById(directory, id, version, { type: 'service' });

/**
* Add a file to a service by it's id.
Expand All @@ -205,10 +141,7 @@ export const rmServiceById = (directory: string) => async (id: string, version?:
*
* ```
*/

export const addFileToService =
(directory: string) => async (id: string, file: { content: string; fileName: string }, version?: string) => {
const pathToEvent = await findFileById(directory, id, version);
if (!pathToEvent) throw new Error('Cannot find directory to write file to');
const contentDirectory = dirname(pathToEvent);
await fs.writeFile(join(contentDirectory, file.fileName), file.content);
};
(directory: string) => async (id: string, file: { content: string; fileName: string }, version?: string) =>
addFileToResource(directory, id, file, version);
6 changes: 6 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export type ResourcePointer = {

export type Message = Event | Command;

enum ResourceType {
Service = 'service',
Event = 'event',
Command = 'command',
}

export interface Event extends BaseSchema {}
export interface Command extends BaseSchema {}

Expand Down
2 changes: 1 addition & 1 deletion tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ export default defineConfig({
sourcemap: true,
clean: true,
dts: true,
entryPoints: ['src/*', '!src/test/*', '!src/docs.ts'],
entry: ['src/*', '!src/test/*', '!src/docs.ts'],
});

0 comments on commit 8550962

Please sign in to comment.