mirror of
https://github.com/dkershner6/post-api-call-action.git
synced 2024-11-15 15:53:51 +08:00
Simple POST api call action
This commit is contained in:
parent
b8934d1b06
commit
42c5911dbd
11
.github/workflows/test.yml
vendored
11
.github/workflows/test.yml
vendored
@ -12,12 +12,5 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- run: |
|
||||
npm install
|
||||
npm run all
|
||||
test: # make sure the action works on a clean machine without building
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: ./
|
||||
with:
|
||||
milliseconds: 1000
|
||||
npm ci
|
||||
npm run all
|
100
README.md
100
README.md
@ -1,101 +1,33 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/actions/typescript-action/actions"><img alt="typescript-action status" src="https://github.com/actions/typescript-action/workflows/build-test/badge.svg"></a>
|
||||
</p>
|
||||
# webhook-action
|
||||
|
||||
# Create a JavaScript Action using TypeScript
|
||||
GitHub Action that sends a POST request of any kind.
|
||||
|
||||
Use this template to bootstrap the creation of a JavaScript action.:rocket:
|
||||
## Inputs
|
||||
|
||||
This template includes compilication support, tests, a validation workflow, publishing, and versioning guidance.
|
||||
### `url`
|
||||
|
||||
If you are new, there's also a simpler introduction. See the [Hello World JavaScript Action](https://github.com/actions/hello-world-javascript-action)
|
||||
**Required**: URL to send post request to.
|
||||
|
||||
## Create an action from this template
|
||||
### `data`
|
||||
|
||||
Click the `Use this Template` and provide the new repo details for your action
|
||||
Optional: JSON string of data to pass into request. Default `"{}"`.
|
||||
|
||||
## Code in Master
|
||||
### `headers`
|
||||
|
||||
Install the dependencies
|
||||
```bash
|
||||
$ npm install
|
||||
```
|
||||
Optional: JSON string of headers to pass into request. Default `"{}"`.
|
||||
|
||||
Build the typescript and package it for distribution
|
||||
```bash
|
||||
$ npm run build && npm run pack
|
||||
```
|
||||
|
||||
Run the tests :heavy_check_mark:
|
||||
```bash
|
||||
$ npm test
|
||||
|
||||
PASS ./index.test.js
|
||||
✓ throws invalid number (3ms)
|
||||
✓ wait 500 ms (504ms)
|
||||
✓ test runs (95ms)
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
## Change action.yml
|
||||
|
||||
The action.yml contains defines the inputs and output for your action.
|
||||
|
||||
Update the action.yml with your name, description, inputs and outputs for your action.
|
||||
|
||||
See the [documentation](https://help.github.com/en/articles/metadata-syntax-for-github-actions)
|
||||
|
||||
## Change the Code
|
||||
|
||||
Most toolkit and CI/CD operations involve async operations so the action is run in an async function.
|
||||
|
||||
```javascript
|
||||
import * as core from '@actions/core';
|
||||
...
|
||||
|
||||
async function run() {
|
||||
try {
|
||||
...
|
||||
}
|
||||
catch (error) {
|
||||
core.setFailed(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
run()
|
||||
```
|
||||
|
||||
See the [toolkit documentation](https://github.com/actions/toolkit/blob/master/README.md#packages) for the various packages.
|
||||
|
||||
## Publish to a distribution branch
|
||||
|
||||
Actions are run from GitHub repos so we will checkin the packed dist folder.
|
||||
|
||||
Then run [ncc](https://github.com/zeit/ncc) and push the results:
|
||||
```bash
|
||||
$ npm run pack
|
||||
$ git add dist
|
||||
$ git commit -a -m "prod dependencies"
|
||||
$ git push origin releases/v1
|
||||
```
|
||||
|
||||
Your action is now published! :rocket:
|
||||
|
||||
See the [versioning documentation](https://github.com/actions/toolkit/blob/master/docs/action-versioning.md)
|
||||
|
||||
## Validate
|
||||
|
||||
You can now validate the action by referencing `./` in a workflow in your repo (see [test.yml](.github/workflows/test.yml)])
|
||||
## Example usage
|
||||
|
||||
```yaml
|
||||
uses: ./
|
||||
uses: dkershner6/post-api-call-action@v1.0.0
|
||||
with:
|
||||
milliseconds: 1000
|
||||
url: ${{ secrets.API_URL }}
|
||||
data: "{'command': 'publish'}"
|
||||
headers: "{'Authorization': '${{ secrets.API_KEY }}'}"
|
||||
```
|
||||
|
||||
See the [actions tab](https://github.com/actions/javascript-action/actions) for runs of this action! :rocket:
|
||||
|
||||
## Usage:
|
||||
## Contributing
|
||||
|
||||
After testing you can [create a v1 tag](https://github.com/actions/toolkit/blob/master/docs/action-versioning.md) to reference the stable and latest V1 action
|
||||
Feel free to open issues or submit PRs.
|
@ -1,14 +0,0 @@
|
||||
import { wait } from '../src/wait';
|
||||
|
||||
test('throws invalid number', async () => {
|
||||
const input = parseInt('foo', 10);
|
||||
await expect(wait(input)).rejects.toThrow('milliseconds not a number');
|
||||
});
|
||||
|
||||
test('wait 500 ms', async () => {
|
||||
const start = new Date();
|
||||
await wait(500);
|
||||
const end = new Date();
|
||||
var delta = Math.abs(end.getTime() - start.getTime());
|
||||
expect(delta).toBeGreaterThan(450);
|
||||
});
|
21
action.yml
21
action.yml
@ -1,10 +1,17 @@
|
||||
name: 'Your name here'
|
||||
description: 'Provide a description here'
|
||||
author: 'Your name or organization here'
|
||||
name: 'POST API Call Action'
|
||||
description: 'Send a POST request'
|
||||
author: 'Derek Kershner'
|
||||
branding:
|
||||
icon: 'bell'
|
||||
color: 'yellow'
|
||||
inputs:
|
||||
myInput: # change this
|
||||
description: 'input description here'
|
||||
default: 'default value if applicable'
|
||||
url:
|
||||
description: 'URL to send post request to'
|
||||
required: true
|
||||
data:
|
||||
description: 'JSON string of data to pass into request'
|
||||
default: '{}'
|
||||
required: false
|
||||
runs:
|
||||
using: 'node12'
|
||||
main: 'dist/index.js'
|
||||
main: 'lib/main.js'
|
330
dist/index.js
vendored
330
dist/index.js
vendored
@ -1,330 +0,0 @@
|
||||
module.exports =
|
||||
/******/ (function(modules, runtime) { // webpackBootstrap
|
||||
/******/ "use strict";
|
||||
/******/ // The module cache
|
||||
/******/ var installedModules = {};
|
||||
/******/
|
||||
/******/ // The require function
|
||||
/******/ function __webpack_require__(moduleId) {
|
||||
/******/
|
||||
/******/ // Check if module is in cache
|
||||
/******/ if(installedModules[moduleId]) {
|
||||
/******/ return installedModules[moduleId].exports;
|
||||
/******/ }
|
||||
/******/ // Create a new module (and put it into the cache)
|
||||
/******/ var module = installedModules[moduleId] = {
|
||||
/******/ i: moduleId,
|
||||
/******/ l: false,
|
||||
/******/ exports: {}
|
||||
/******/ };
|
||||
/******/
|
||||
/******/ // Execute the module function
|
||||
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
|
||||
/******/
|
||||
/******/ // Flag the module as loaded
|
||||
/******/ module.l = true;
|
||||
/******/
|
||||
/******/ // Return the exports of the module
|
||||
/******/ return module.exports;
|
||||
/******/ }
|
||||
/******/
|
||||
/******/
|
||||
/******/ __webpack_require__.ab = __dirname + "/";
|
||||
/******/
|
||||
/******/ // the startup function
|
||||
/******/ function startup() {
|
||||
/******/ // Load entry module and return exports
|
||||
/******/ return __webpack_require__(198);
|
||||
/******/ };
|
||||
/******/
|
||||
/******/ // run startup
|
||||
/******/ return startup();
|
||||
/******/ })
|
||||
/************************************************************************/
|
||||
/******/ ({
|
||||
|
||||
/***/ 87:
|
||||
/***/ (function(module) {
|
||||
|
||||
module.exports = require("os");
|
||||
|
||||
/***/ }),
|
||||
|
||||
/***/ 198:
|
||||
/***/ (function(__unusedmodule, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const core = __importStar(__webpack_require__(470));
|
||||
const wait_1 = __webpack_require__(521);
|
||||
function run() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const ms = core.getInput('milliseconds');
|
||||
core.debug(`Waiting ${ms} milliseconds ...`);
|
||||
core.debug(new Date().toTimeString());
|
||||
yield wait_1.wait(parseInt(ms, 10));
|
||||
core.debug(new Date().toTimeString());
|
||||
core.setOutput('time', new Date().toTimeString());
|
||||
}
|
||||
catch (error) {
|
||||
core.setFailed(error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
run();
|
||||
|
||||
|
||||
/***/ }),
|
||||
|
||||
/***/ 431:
|
||||
/***/ (function(__unusedmodule, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const os = __webpack_require__(87);
|
||||
/**
|
||||
* Commands
|
||||
*
|
||||
* Command Format:
|
||||
* ##[name key=value;key=value]message
|
||||
*
|
||||
* Examples:
|
||||
* ##[warning]This is the user warning message
|
||||
* ##[set-secret name=mypassword]definatelyNotAPassword!
|
||||
*/
|
||||
function issueCommand(command, properties, message) {
|
||||
const cmd = new Command(command, properties, message);
|
||||
process.stdout.write(cmd.toString() + os.EOL);
|
||||
}
|
||||
exports.issueCommand = issueCommand;
|
||||
function issue(name, message) {
|
||||
issueCommand(name, {}, message);
|
||||
}
|
||||
exports.issue = issue;
|
||||
const CMD_PREFIX = '##[';
|
||||
class Command {
|
||||
constructor(command, properties, message) {
|
||||
if (!command) {
|
||||
command = 'missing.command';
|
||||
}
|
||||
this.command = command;
|
||||
this.properties = properties;
|
||||
this.message = message;
|
||||
}
|
||||
toString() {
|
||||
let cmdStr = CMD_PREFIX + this.command;
|
||||
if (this.properties && Object.keys(this.properties).length > 0) {
|
||||
cmdStr += ' ';
|
||||
for (const key in this.properties) {
|
||||
if (this.properties.hasOwnProperty(key)) {
|
||||
const val = this.properties[key];
|
||||
if (val) {
|
||||
// safely append the val - avoid blowing up when attempting to
|
||||
// call .replace() if message is not a string for some reason
|
||||
cmdStr += `${key}=${escape(`${val || ''}`)};`;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cmdStr += ']';
|
||||
// safely append the message - avoid blowing up when attempting to
|
||||
// call .replace() if message is not a string for some reason
|
||||
const message = `${this.message || ''}`;
|
||||
cmdStr += escapeData(message);
|
||||
return cmdStr;
|
||||
}
|
||||
}
|
||||
function escapeData(s) {
|
||||
return s.replace(/\r/g, '%0D').replace(/\n/g, '%0A');
|
||||
}
|
||||
function escape(s) {
|
||||
return s
|
||||
.replace(/\r/g, '%0D')
|
||||
.replace(/\n/g, '%0A')
|
||||
.replace(/]/g, '%5D')
|
||||
.replace(/;/g, '%3B');
|
||||
}
|
||||
//# sourceMappingURL=command.js.map
|
||||
|
||||
/***/ }),
|
||||
|
||||
/***/ 470:
|
||||
/***/ (function(__unusedmodule, exports, __webpack_require__) {
|
||||
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const command_1 = __webpack_require__(431);
|
||||
const path = __webpack_require__(622);
|
||||
/**
|
||||
* The code to exit an action
|
||||
*/
|
||||
var ExitCode;
|
||||
(function (ExitCode) {
|
||||
/**
|
||||
* A code indicating that the action was successful
|
||||
*/
|
||||
ExitCode[ExitCode["Success"] = 0] = "Success";
|
||||
/**
|
||||
* A code indicating that the action was a failure
|
||||
*/
|
||||
ExitCode[ExitCode["Failure"] = 1] = "Failure";
|
||||
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
|
||||
//-----------------------------------------------------------------------
|
||||
// Variables
|
||||
//-----------------------------------------------------------------------
|
||||
/**
|
||||
* sets env variable for this action and future actions in the job
|
||||
* @param name the name of the variable to set
|
||||
* @param val the value of the variable
|
||||
*/
|
||||
function exportVariable(name, val) {
|
||||
process.env[name] = val;
|
||||
command_1.issueCommand('set-env', { name }, val);
|
||||
}
|
||||
exports.exportVariable = exportVariable;
|
||||
/**
|
||||
* exports the variable and registers a secret which will get masked from logs
|
||||
* @param name the name of the variable to set
|
||||
* @param val value of the secret
|
||||
*/
|
||||
function exportSecret(name, val) {
|
||||
exportVariable(name, val);
|
||||
command_1.issueCommand('set-secret', {}, val);
|
||||
}
|
||||
exports.exportSecret = exportSecret;
|
||||
/**
|
||||
* Prepends inputPath to the PATH (for this action and future actions)
|
||||
* @param inputPath
|
||||
*/
|
||||
function addPath(inputPath) {
|
||||
command_1.issueCommand('add-path', {}, inputPath);
|
||||
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
|
||||
}
|
||||
exports.addPath = addPath;
|
||||
/**
|
||||
* Gets the value of an input. The value is also trimmed.
|
||||
*
|
||||
* @param name name of the input to get
|
||||
* @param options optional. See InputOptions.
|
||||
* @returns string
|
||||
*/
|
||||
function getInput(name, options) {
|
||||
const val = process.env[`INPUT_${name.replace(' ', '_').toUpperCase()}`] || '';
|
||||
if (options && options.required && !val) {
|
||||
throw new Error(`Input required and not supplied: ${name}`);
|
||||
}
|
||||
return val.trim();
|
||||
}
|
||||
exports.getInput = getInput;
|
||||
/**
|
||||
* Sets the value of an output.
|
||||
*
|
||||
* @param name name of the output to set
|
||||
* @param value value to store
|
||||
*/
|
||||
function setOutput(name, value) {
|
||||
command_1.issueCommand('set-output', { name }, value);
|
||||
}
|
||||
exports.setOutput = setOutput;
|
||||
//-----------------------------------------------------------------------
|
||||
// Results
|
||||
//-----------------------------------------------------------------------
|
||||
/**
|
||||
* Sets the action status to failed.
|
||||
* When the action exits it will be with an exit code of 1
|
||||
* @param message add error issue message
|
||||
*/
|
||||
function setFailed(message) {
|
||||
process.exitCode = ExitCode.Failure;
|
||||
error(message);
|
||||
}
|
||||
exports.setFailed = setFailed;
|
||||
//-----------------------------------------------------------------------
|
||||
// Logging Commands
|
||||
//-----------------------------------------------------------------------
|
||||
/**
|
||||
* Writes debug message to user log
|
||||
* @param message debug message
|
||||
*/
|
||||
function debug(message) {
|
||||
command_1.issueCommand('debug', {}, message);
|
||||
}
|
||||
exports.debug = debug;
|
||||
/**
|
||||
* Adds an error issue
|
||||
* @param message error issue message
|
||||
*/
|
||||
function error(message) {
|
||||
command_1.issue('error', message);
|
||||
}
|
||||
exports.error = error;
|
||||
/**
|
||||
* Adds an warning issue
|
||||
* @param message warning issue message
|
||||
*/
|
||||
function warning(message) {
|
||||
command_1.issue('warning', message);
|
||||
}
|
||||
exports.warning = warning;
|
||||
//# sourceMappingURL=core.js.map
|
||||
|
||||
/***/ }),
|
||||
|
||||
/***/ 521:
|
||||
/***/ (function(__unusedmodule, exports) {
|
||||
|
||||
"use strict";
|
||||
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
function wait(milliseconds) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
return new Promise(resolve => {
|
||||
if (isNaN(milliseconds)) {
|
||||
throw new Error('milliseconds not a number');
|
||||
}
|
||||
setTimeout(() => resolve('done!'), milliseconds);
|
||||
});
|
||||
});
|
||||
}
|
||||
exports.wait = wait;
|
||||
|
||||
|
||||
/***/ }),
|
||||
|
||||
/***/ 622:
|
||||
/***/ (function(module) {
|
||||
|
||||
module.exports = require("path");
|
||||
|
||||
/***/ })
|
||||
|
||||
/******/ });
|
3865
package-lock.json
generated
3865
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
41
package.json
41
package.json
@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "typescript-action",
|
||||
"version": "0.0.0",
|
||||
"name": "post-api-call-action",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "TypeScript template action",
|
||||
"description": "Send a POST request action",
|
||||
"main": "lib/main.js",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
@ -10,36 +10,37 @@
|
||||
"format-check": "prettier --check **/*.ts",
|
||||
"lint": "eslint src/**/*.ts",
|
||||
"pack": "ncc build",
|
||||
"test": "jest",
|
||||
"test": "jest --passWithNoTests",
|
||||
"all": "npm run build && npm run format && npm run lint && npm run pack && npm test"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/actions/typescript-action.git"
|
||||
"url": "git+https://github.com/dkershner6/post-api-call-action.git"
|
||||
},
|
||||
"keywords": [
|
||||
"actions",
|
||||
"node",
|
||||
"setup"
|
||||
],
|
||||
"author": "YourNameOrOrganization",
|
||||
"author": "Derek Kershner",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.2.4"
|
||||
"@actions/core": "^1.3.0",
|
||||
"axios": "^0.21.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^26.0.0",
|
||||
"@types/node": "^14.0.13",
|
||||
"@typescript-eslint/parser": "^3.2.0",
|
||||
"@zeit/ncc": "^0.22.3",
|
||||
"eslint": "^7.2.0",
|
||||
"eslint-plugin-github": "^4.0.1",
|
||||
"eslint-plugin-jest": "^23.13.2",
|
||||
"jest": "^26.0.1",
|
||||
"jest-circus": "^26.0.1",
|
||||
"js-yaml": "^3.14.0",
|
||||
"prettier": "^2.0.5",
|
||||
"ts-jest": "^26.1.0",
|
||||
"typescript": "^3.9.5"
|
||||
"@types/jest": "^26.0.23",
|
||||
"@types/node": "^15.6.0",
|
||||
"@typescript-eslint/parser": "^4.24.0",
|
||||
"@vercel/ncc": "^0.28.5",
|
||||
"eslint": "^7.26.0",
|
||||
"eslint-plugin-github": "^4.1.3",
|
||||
"eslint-plugin-jest": "^24.3.6",
|
||||
"jest": "^26.6.3",
|
||||
"jest-circus": "^26.6.3",
|
||||
"js-yaml": "^4.1.0",
|
||||
"prettier": "^2.3.0",
|
||||
"ts-jest": "^26.5.6",
|
||||
"typescript": "^4.2.4"
|
||||
}
|
||||
}
|
||||
|
37
src/main.ts
37
src/main.ts
@ -1,19 +1,26 @@
|
||||
import * as core from '@actions/core'
|
||||
import {wait} from './wait'
|
||||
import { getInput, info, setFailed } from '@actions/core';
|
||||
import axios from 'axios';
|
||||
|
||||
const parseJsonSafely = (jsonString: string): any => {
|
||||
try {
|
||||
return JSON.parse(jsonString);
|
||||
} catch (error) {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
async function run(): Promise<void> {
|
||||
try {
|
||||
const ms: string = core.getInput('milliseconds')
|
||||
core.debug(`Waiting ${ms} milliseconds ...`)
|
||||
|
||||
core.debug(new Date().toTimeString())
|
||||
await wait(parseInt(ms, 10))
|
||||
core.debug(new Date().toTimeString())
|
||||
|
||||
core.setOutput('time', new Date().toTimeString())
|
||||
} catch (error) {
|
||||
core.setFailed(error.message)
|
||||
}
|
||||
try {
|
||||
const url: string = getInput('url');
|
||||
info('Sending POST request...');
|
||||
const data = parseJsonSafely(getInput('data'));
|
||||
const headers = parseJsonSafely(getInput('headers'));
|
||||
await axios.post(url, data, {
|
||||
headers,
|
||||
});
|
||||
} catch (error) {
|
||||
setFailed(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
run()
|
||||
run();
|
||||
|
@ -1,9 +0,0 @@
|
||||
export async function wait(milliseconds: number): Promise<string> {
|
||||
return new Promise(resolve => {
|
||||
if (isNaN(milliseconds)) {
|
||||
throw new Error('milliseconds not a number')
|
||||
}
|
||||
|
||||
setTimeout(() => resolve('done!'), milliseconds)
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user