Filer
Provides an API for accessing parsed file content in a collection-like file structure.
Installation
npm i @cloudcannon/filer
Usage
JavaScript-based SSGs often have no standard approach to reading content from local files. This package aims to address this.
This package assumes a file structure where files are grouped into top-level folders called collections.
This mimics the file structure seen in a number of SSGs with standard approaches to reading local files.
Here's an example file tree with three collections inside a content
folder:
content
├── pages
│ ├── about.md
│ └── index.md
├── posts
│ ├── my-first-post.md
│ ├── another-post.md
│ └── my-last-post-ever.md
└── authors
├── jane.md
└── john.md
At the moment, this is limited to Markdown files only.
Setup
Where these functions are called depends on the SSG you are using.
This package simply wraps file reading and parsing into a consistent API.
import Filer from '@cloudcannon/filer';
const filer = new Filer({
path: 'content'
});
Getting all parsed items in collection
await filer.getItems('posts');
await filer.getItems('posts', {
excerpt: true,
sortKey: 'date',
sortReverse: true
});
Getting filtered items in a collection
You can provide a filter
function to the options
object.
This function should return a boolean value. The item will be returned if filter
returns true
.
await filer.getItems('posts', {
filter: (item) => {
return item.data.tags.includes('category');
}
});
Getting paginated items in collection
await filer.getPaginatedItems('posts', {
sortKey: 'date',
pagination: {
size: 10,
page: 3
}
});
If the page
requested is greater than the number of pages, will return the last page.
If the size
requested is greater than the number of items, will return one page with all items.
This function returns data in the following format:
{
data: [],
start: 20,
end: 29,
total: 42,
currentPage: 3,
size: 10,
lastPage: 5,
prevPage: 2,
nextPage: 4
};
Getting one parsed item in collection
await filer.getItem('my-first-post.md', { folder: 'posts' });
await filer.getItem('my-first-post.md', {
folder: 'posts',
excerpt: true
});
Listing slugs for a collection
This is useful for providing Next.js with static paths.
await filer.listItemSlugs('posts');
Development
Install dependencies:
$ npm i
Run tests:
$ npm test
$ npm run test:watch
$ npm run test:coverage
Lint code:
$ npm run lint
License
MIT