@akikungz/warpper-ts
v1.0.4
Published
A TypeScript wrapper utility
Readme
warpper-ts
A TypeScript wrapper utility package that provides error-safe function execution. Instead of throwing exceptions, it returns a tuple with either an error or result, similar to Go's error handling pattern.
Installation
npm install @akikungz/warpper-tsUsage
Basic Import
import { warpper } from '@akikungz/warpper-ts';Simple Functions
// Synchronous function
const [error, result] = await warpper(() => 42);
if (error) {
console.error('Error:', error.message);
} else {
console.log('Result:', result); // 42
}Async Functions
// Asynchronous function
const [error, data] = await warpper(async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
});
if (error) {
console.error('API call failed:', error.message);
} else {
console.log('Data received:', data);
}Functions with Parameters
// Function with parameters
const divide = (a: number, b: number) => {
if (b === 0) throw new Error('Division by zero');
return a / b;
};
const [error, result] = await warpper(divide, [10, 2]);
if (error) {
console.error('Division failed:', error.message);
} else {
console.log('Result:', result); // 5
}Error Handling
// Function that throws an error
const riskyFunction = () => {
throw new Error('Something went wrong!');
};
const [error, result] = await warpper(riskyFunction);
console.log(error?.message); // "Something went wrong!"
console.log(result); // nullReal-world Example
import { warpper } from '@akikungz/warpper-ts';
import fs from 'fs/promises';
async function readConfigFile(filename: string) {
const [readError, content] = await warpper(fs.readFile, [filename, 'utf8']);
if (readError) {
return [readError, null];
}
const [parseError, config] = await warpper(JSON.parse, [content]);
if (parseError) {
return [new Error(`Invalid JSON in ${filename}: ${parseError.message}`), null];
}
return [null, config];
}
// Usage
const [error, config] = await readConfigFile('config.json');
if (error) {
console.error('Failed to load config:', error.message);
process.exit(1);
} else {
console.log('Config loaded successfully:', config);
}TypeScript Support
The package includes full TypeScript support with proper type inference:
// Type inference works automatically
const [error, num] = await warpper(() => 42);
// num is inferred as number
const [error, str] = await warpper(async () => 'hello');
// str is inferred as string
// Custom error types
class CustomError extends Error {
code: number;
constructor(message: string, code: number) {
super(message);
this.code = code;
}
}
const throwCustomError = () => {
throw new CustomError('Custom error', 404);
};
const [error, result] = await warpper<typeof throwCustomError, CustomError>(throwCustomError);
// error is typed as CustomError | nullAPI Reference
warpper<TFunction, TError, TResult>(callback, args?)
Executes a callback function and returns a promise that resolves with a tuple containing an error (if any) and the result.
Parameters
callback: TFunction- The function to executeargs?: Parameters<TFunction>- Optional array of arguments to pass to the callback function
Returns
Promise<[TError | null, TResult]> - A tuple where:
- First element: Error object if the function throws,
nullif successful - Second element: Function result if successful,
nullif an error occurred
Type Parameters
TFunction extends (...args: any[]) => any- The callback function typeTError extends Error = Error- The expected error type (defaults to Error)TResult- The return type (automatically inferred from TFunction)
GitHub Actions Setup
This repository includes automated CI/CD workflows using GitHub Actions for testing and publishing to npm.
Workflows
CI Workflow (
.github/workflows/ci.yml)- Runs on push/PR to main/master branches
- Tests against Node.js versions 18.x, 20.x, and 22.x
- Runs tests and builds the package
Publish Workflow (
.github/workflows/publish.yml)- Triggers when a GitHub release is published
- Runs tests, builds, and publishes to npm
Version and Release Workflow (
.github/workflows/version-and-release.yml)- Auto-bumps version based on conventional commits
- Creates GitHub releases automatically
Setup Instructions
1. NPM Token Setup
To enable automatic publishing to npm, you need to set up an NPM token:
- Go to npmjs.com and log in
- Go to Access Tokens in your account settings
- Create a new token with "Automation" type
- In your GitHub repository, go to Settings → Secrets and variables → Actions
- Create a new repository secret named
NPM_TOKENwith your token value
2. Repository Permissions
Make sure your repository has the following permissions:
- Go to Settings → Actions → General
- Set "Workflow permissions" to "Read and write permissions"
- Check "Allow GitHub Actions to create and approve pull requests"
3. Branch Protection (Optional but Recommended)
- Go to Settings → Branches
- Add a branch protection rule for
main(ormaster) - Require status checks to pass before merging
- Require branches to be up to date before merging
How It Works
Automatic Testing
- Every push or pull request triggers the CI workflow
- Tests run on multiple Node.js versions
- Build verification ensures the package compiles correctly
Automatic Publishing
- Create a new release on GitHub (either manually or automatically)
- The publish workflow will automatically:
- Run tests
- Build the package
- Publish to npm with the version from package.json
Automatic Versioning (Optional)
- The version-and-release workflow can automatically bump versions based on commit messages
- Use conventional commit messages:
feat:for minor version bumpsfix:for patch version bumpsBREAKING CHANGE:for major version bumps
Manual Release Process
Update the version in
package.json:npm version patch # or minor, majorPush the changes:
git push git push --tagsCreate a release on GitHub:
- Go to Releases → Create a new release
- Choose the tag you just pushed
- Add release notes
- Publish the release
The publish workflow will automatically run and publish to npm
Local Development
# Install dependencies
npm install
# Run tests
npm test
# Build the package
npm run build
# Test publishing (dry run)
npm publish --dry-runPackage Information
- Name:
@akikungz/warpper-ts - Registry: npm (public)
- Built with: TypeScript
- Tested with: Jest
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests:
npm test - Build the package:
npm run build - Submit a pull request
The CI workflow will automatically test your changes across multiple Node.js versions.
