Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
GriffinSauce committed Aug 11, 2020
0 parents commit 9d33356
Show file tree
Hide file tree
Showing 11 changed files with 6,541 additions and 0 deletions.
42 changes: 42 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest

steps:
- name: Begin CI...
uses: actions/checkout@v2

- name: Use Node 12
uses: actions/setup-node@v1
with:
node-version: 12.x

- name: Use cached node_modules
uses: actions/cache@v1
with:
path: node_modules
key: nodeModules-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
nodeModules-
- name: Install dependencies
run: yarn install --frozen-lockfile
env:
CI: true

- name: Lint
run: yarn lint
env:
CI: true

- name: Test
run: yarn test --ci --coverage --maxWorkers=2
env:
CI: true

- name: Build
run: yarn build
env:
CI: true
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.log
.DS_Store
node_modules
dist
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 GriffinSauce

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
82 changes: 82 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# 💨 luft

An extremely simple Airtable client for JavaScript.

## WARNING!

⚠️ This library is highly experimental, UNTESTED and likely to have breaking changes. It is not recommended to use it for anything serious. Unserious and mischievious use is encouraged.

## Install

```.sh
yarn add luft

// or

npm install luft
```

## Usage

An example that utilizes most options:

```.js
import { initialize, get } from '../utils/airtable';

initialize({
baseId: '<your base id>',
apiKey: '<your api key>',
});

const getUpcomingShows = async () => {
let records;
try {
records = await get('Shows', {
sort: [{ field: 'Date', direction: 'desc' }],
populate: [
{
path: 'Venue',
from: 'Venues',
multi: false,
fields: ['Address', 'City', 'Name'],
},
{
path: 'With',
from: 'Bands',
multi: true,
fields: ['Name']
},
],
filter: 'IS_AFTER({Date}, NOW())',
toObject: true,
});
} catch (err) {
console.error(err);
throw new Error(`Fetching shows failed`);
}
return records;
};
```

TODO: document all functions and params

## Local Development

### `yarn dev`

Runs the project in development/watch mode. The project will be rebuilt upon changes.

### `yarn build`

Bundles the package to the `dist` folder.
The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).

### `yarn test`

Runs the test watcher (Jest) in an interactive mode.

## Notes

This project was bootstrapped with [TSDX](https://github.com/jaredpalmer/tsdx).

Some inspiration taken from https://github.com/Arro/airtable-json
50 changes: 50 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"version": "0.1.0",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=10"
},
"scripts": {
"dev": "tsdx watch",
"build": "tsdx build",
"test": "tsdx test",
"lint": "tsdx lint",
"prepare": "tsdx build"
},
"peerDependencies": {},
"husky": {
"hooks": {
"pre-commit": "tsdx lint"
}
},
"prettier": {
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
},
"name": "luft",
"author": "GriffinSauce",
"module": "dist/luft.esm.js",
"devDependencies": {
"husky": "^4.2.5",
"tsdx": "^0.13.2",
"tslib": "^2.0.1",
"typescript": "^3.9.7"
},
"dependencies": {
"@types/airtable": "^0.8.0",
"@types/lodash.camelcase": "^4.3.6",
"@types/lodash.isobject": "^3.0.6",
"airtable": "^0.9.0",
"awaity": "^1.0.0",
"lodash.camelcase": "^4.3.0",
"lodash.isobject": "^3.0.2"
}
}
171 changes: 171 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import Airtable, { Base, Record, SortParameter } from 'airtable';
import reduce from 'awaity/reduce';
import { recordToObject } from './utils';

export { recordToObject } from './utils';

// TODO: Input checks
// TODO: Error handling
// TODO: Document params
// TODO: Test things...

type PopulateFieldType = {
path: string;
from: string;
multi: boolean;
fields: Array<string>;
};

type PopulateType = Array<PopulateFieldType>;

let base: Base;

// Go nuts, you got this!
export const getBase = () => {
return base;
};

export const initialize = ({
baseId,
apiKey,
}: {
baseId: string;
apiKey: string;
}) => {
if (!baseId) throw new Error(`"baseId" is required `);
if (!apiKey) throw new Error(`"apiKey" is required `);

// @ts-ignore - missing in types
Airtable.configure({ apiKey });
// @ts-ignore - missing in types
base = Airtable.base(baseId);
};

const populateField = async (
record: Record<any>,
{ path, from, multi, fields }: PopulateFieldType
) => {
// @ts-ignore - missing in types
const ref = record.get(path);
if (!ref) return record;
let result = ref;

try {
/* eslint-disable no-use-before-define */
result = multi
? await get(from, {
filter: `OR(${ref
.map((recordId: string) => `RECORD_ID()="${recordId}"`)
.join(',')})`,
fields,
})
: await getById(from, {
recordId: ref,
fields,
});
/* eslint-enable no-use-before-define */
} catch (err) {
console.error(
`Failed to populate ${path} of ${record.id}\n ${err.message}`
);
}

// Don't recreate an object here because we're dealing with a record
record.fields[path] = result; // eslint-disable-line no-param-reassign
return record;
};

const populateRecord = (
record: Record<any>,
populate: PopulateType
): Record<any> => reduce(populate, populateField, record); // Reduce with promises

export const getById = async (
tableId: string,
{
recordId,
fields,
populate,
toObject,
}: {
recordId: string;
fields?: Array<string>;
populate?: PopulateType;
toObject?: boolean;
}
) => {
const [record] = await base(tableId)
.select({
filterByFormula: `RECORD_ID()="${recordId}"`, // Can't select fields with a find operation
...(fields ? { fields } : {}),
})
.firstPage();

let populated = record;
if (populate) populated = await populateRecord(record, populate);

return toObject ? recordToObject(populated) : populated;
};

export const getByField = async (
tableId: string,
{
key,
field,
fields,
populate,
toObject,
}: {
key: string;
field: string;
fields?: Array<string>;
populate?: PopulateType;
toObject?: boolean;
}
) => {
const [record] = await base(tableId)
.select({
filterByFormula: `${field}="${key}"`,
...(fields ? { fields } : {}),
})
.firstPage();

let populated = record;
if (populate) populated = await populateRecord(record, populate);

return toObject ? recordToObject(populated) : populated;
};

export const get = async (
tableId: string,
{
sort,
fields,
filter,
populate,
toObject,
}: {
sort?: Array<SortParameter>;
filter?: string;
fields?: Array<string>;
populate?: PopulateType;
toObject?: boolean;
}
) => {
const records = await base(tableId)
.select({
...(sort ? { sort } : {}),
...(fields ? { fields } : {}),
...(filter ? { filterByFormula: filter } : {}),
})
.all();

let populated = records;
if (populate) {
populated = await Promise.all(
records.map(record => populateRecord(record, populate))
);
}

return toObject ? populated.map(recordToObject) : populated;
};
Loading

0 comments on commit 9d33356

Please sign in to comment.