Skip to content

Commit

Permalink
ci: #174 Prettier setup (#169)
Browse files Browse the repository at this point in the history
* removed tslint

* add eslint

* add default config

* setup default config and npm run command

* add command to node.js.yml

* set rules to support current codebase

* remove unused tslint.json

* include sample files in eslint command

* remove rule no-explicit-any

* specify type for timer

* remove any from filterKeys

* explictly declare that error can be Error, String but still accept any from the end users

* specify types in the sync worker

* improve the IndexableError type

* explain why any is allowed in CustomData

* remove no-this-alias from eslint config

* convert to arrow function to preserve this reference

* use arrow functions to remove the need of a this alias

* define httpoptions object instead of using this alias

* add examples to prettier command

* add prettier job to node js ci job

* script fix

* setup no-unused-vars lint rule

* remove unused var

* fixed lib/raygun.batch.ts

* fix lib/raygun.offline.ts

* cleanup lib/raygun.sync.transport.ts

* fix lib/raygun.transport.ts

* fix lib/raygun.ts

* fix @typescript-eslint/no-unused-vars

* fixs in test files

* update package lock in sample

* cleanup eslint config

* config files

* run npm run prettier

* Update .github/workflows/node.js.yml

Co-authored-by: Sumitra Manga <[email protected]>

* fix workflow

* add comments to the package.json

* add missing files

* remove fetch-depth: 0

---------

Co-authored-by: Sumitra Manga <[email protected]>
  • Loading branch information
miquelbeltran and sumitramanga authored May 1, 2024
1 parent b790fbf commit 3def9b9
Show file tree
Hide file tree
Showing 22 changed files with 191 additions and 164 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,27 @@ jobs:
- run: npm ci
- run: npm test
- run: npm run eslint

# Checks code formatting, fails if there are changes after applying prettier.
# Based on this example here:
# https://github.com/creyD/prettier_action?tab=readme-ov-file#example-4-dry-run
prettier:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3
with:
# Make sure the actual branch is checked out when running on pull requests
ref: ${{ github.head_ref }}
# Make sure the value of GITHUB_TOKEN will not be persisted in repo's config
persist-credentials: false

- name: Prettify code
uses: creyD/[email protected]
with:
# "dry" causes that if any file is modified, the job fails
dry: True
# "write" performs changes in place
prettier_options: --write lib/*.ts test/*.js examples/**/*.js
github_token: ${{ secrets.PERSONAL_GITHUB_TOKEN }}
70 changes: 37 additions & 33 deletions examples/express-sample/app.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,60 @@
var config = require('config');
var config = require("config");

if (config.Raygun.Key === 'YOUR_API_KEY') {
console.error('You need to set your Raygun API key in the config file');
process.exit(1);
if (config.Raygun.Key === "YOUR_API_KEY") {
console.error("You need to set your Raygun API key in the config file");
process.exit(1);
}

// Setup Raygun
var raygun = require('raygun');
var raygun = require("raygun");
var raygunClient = new raygun.Client().init({
apiKey: config.Raygun.Key
apiKey: config.Raygun.Key,
});

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var sassMiddleware = require('node-sass-middleware');
var express = require("express");
var path = require("path");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var sassMiddleware = require("node-sass-middleware");

var routes = require('./routes/index');
var users = require('./routes/users');
var routes = require("./routes/index");
var users = require("./routes/users");

var app = express();

// Set the user if we have one
raygunClient.user = function(req) {
return '[email protected]';
raygunClient.user = function (req) {
return "[email protected]";
};

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(
bodyParser.urlencoded({
extended: false,
}),
);
app.use(cookieParser());
app.use(sassMiddleware({
src: __dirname,
dest: path.join(__dirname, 'public'),
debug: true,
outputStyle: 'compressed',
prefix: '/stylesheets'
}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use(
sassMiddleware({
src: __dirname,
dest: path.join(__dirname, "public"),
debug: true,
outputStyle: "compressed",
prefix: "/stylesheets",
}),
);
app.use(express.static(path.join(__dirname, "public")));

app.use("/", routes);
app.use("/users", users);

// Add the Raygun Express handler
app.use(raygunClient.expressHandler);
Expand Down
20 changes: 10 additions & 10 deletions examples/express-sample/routes/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
var express = require('express');
var express = require("express");
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Express'
});
router.get("/", function (req, res, next) {
res.render("index", {
title: "Express",
});
});

router.get('/error', function(req, res, next) {
// Call an object that doesn't exist to send an error to Raygun
fakeObject.FakeMethod();
res.send(500);
router.get("/error", function (req, res, next) {
// Call an object that doesn't exist to send an error to Raygun
fakeObject.FakeMethod();
res.send(500);
});

module.exports = router;
module.exports = router;
6 changes: 3 additions & 3 deletions examples/express-sample/routes/users.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
var express = require('express');
var express = require("express");
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
router.get("/", function (req, res, next) {
res.send("respond with a resource");
});

module.exports = router;
70 changes: 35 additions & 35 deletions examples/using-domains/app.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,52 @@
var config = require('config');
var config = require("config");

if (config.Raygun.Key === 'YOUR_API_KEY') {
console.error('You need to set your Raygun API key in the config file');
process.exit(1);
if (config.Raygun.Key === "YOUR_API_KEY") {
console.error("You need to set your Raygun API key in the config file");
process.exit(1);
}

// Setup Raygun
var raygun = require('raygun');
var raygunClient = new raygun.Client().init({apiKey: config.Raygun.Key});
var raygun = require("raygun");
var raygunClient = new raygun.Client().init({ apiKey: config.Raygun.Key });

// Create a domain
var appDomain = require('domain').create();
var appDomain = require("domain").create();

// Add the error handler so we can pass errors to Raygun when the domain
// crashes
appDomain.on('error', function (err) {
try {
console.log(`Domain error caught: ${err}`);
// Try send data to Raygun
raygunClient.send(err, {}, function () {
// Exit the process once the error has been sent
console.log('Error sent to Raygun, exiting process');
process.exit(1);
});
} catch (e) {
// If there was an error sending to Raygun, log it out and end the process.
// Could possibly log out to a text file here
console.log(e);
process.exit(1);
}
appDomain.on("error", function (err) {
try {
console.log(`Domain error caught: ${err}`);
// Try send data to Raygun
raygunClient.send(err, {}, function () {
// Exit the process once the error has been sent
console.log("Error sent to Raygun, exiting process");
process.exit(1);
});
} catch (e) {
// If there was an error sending to Raygun, log it out and end the process.
// Could possibly log out to a text file here
console.log(e);
process.exit(1);
}
});

// Run the domain
appDomain.run(function () {
var fs = require('fs');
var fs = require("fs");

console.log('Running example app');
console.log("Running example app");

// Try and read a file that doesn't exist
fs.readFile('badfile.json', 'utf8', function (err, file) {
if (err) {
// We could send the error straight to Raygun
// raygunClient.send(err);
// Try and read a file that doesn't exist
fs.readFile("badfile.json", "utf8", function (err, file) {
if (err) {
// We could send the error straight to Raygun
// raygunClient.send(err);

// Or we can deal with it in our "Fake Error Handler" below
// Or we can deal with it in our "Fake Error Handler" below

// This will throw an error as fakeErrorHandler doesn't exist
fakeErrorHandler.DealWith(err);
}
})
});
// This will throw an error as fakeErrorHandler doesn't exist
fakeErrorHandler.DealWith(err);
}
});
});
14 changes: 7 additions & 7 deletions lib/raygun.batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,15 @@ export class RaygunBatchTransport {
}

private onIncomingMessage(messageAndCallback: MessageAndCallback) {
const { serializedMessage} = messageAndCallback;
const { serializedMessage } = messageAndCallback;
const messageLength = Buffer.byteLength(serializedMessage, "utf-8");

if (messageLength >= MAX_BATCH_INNER_SIZE_BYTES) {
const messageSize = Math.ceil(messageLength / 1024);
const startOfMessage = serializedMessage.slice(0, 1000);

console.warn(
`[raygun4node] Error is too large to send to Raygun (${messageSize}kb)\nStart of error: ${startOfMessage}`
`[raygun4node] Error is too large to send to Raygun (${messageSize}kb)\nStart of error: ${startOfMessage}`,
);

return;
Expand Down Expand Up @@ -123,7 +123,7 @@ export class RaygunBatchTransport {
const { payload, messageCount, callbacks } = batch;

debug(
`batch transport - processing ( ${messageCount} message(s) in batch)`
`batch transport - processing ( ${messageCount} message(s) in batch)`,
);

const batchId = this.batchId;
Expand All @@ -132,16 +132,16 @@ export class RaygunBatchTransport {

const runAllCallbacks = (
err: Error | null,
response: IncomingMessage | null
response: IncomingMessage | null,
) => {
const durationInMs = stopTimer();
if (err) {
debug(
`batch transport - error sending batch (id=${batchId}, duration=${durationInMs}ms): ${err}`
`batch transport - error sending batch (id=${batchId}, duration=${durationInMs}ms): ${err}`,
);
} else {
debug(
`batch transport - successfully sent batch (id=${batchId}, duration=${durationInMs}ms)`
`batch transport - successfully sent batch (id=${batchId}, duration=${durationInMs}ms)`,
);
}

Expand All @@ -153,7 +153,7 @@ export class RaygunBatchTransport {
};

debug(
`batch transport - sending batch (id=${batchId}) (${messageCount} messages, ${payload.length} bytes)`
`batch transport - sending batch (id=${batchId}) (${messageCount} messages, ${payload.length} bytes)`,
);

const stopTimer = startTimer();
Expand Down
4 changes: 2 additions & 2 deletions lib/raygun.messageBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function filterKeys(obj: object, filters: string[]): object {

function getStackTrace(
error: Error,
options: MessageBuilderOptions
options: MessageBuilderOptions,
): StackFrame[] {
const stack: StackFrame[] = [];
const trace = stackTrace.parse(error);
Expand Down Expand Up @@ -78,7 +78,7 @@ function getStackTrace(

function buildError(
error: IndexableError,
options: MessageBuilderOptions
options: MessageBuilderOptions,
): BuiltError {
const builtError: BuiltError = {
stackTrace: getStackTrace(error, options),
Expand Down
21 changes: 11 additions & 10 deletions lib/raygun.offline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,14 @@ export class OfflineStorage implements IOfflineStorage {
}

private _sendAndDelete(item: string) {
fs.readFile(path.join(this.cachePath, item), "utf8", (
err,
cacheContents
) => {
this.transport.send(cacheContents);
fs.unlink(path.join(this.cachePath, item), () => {});
});
fs.readFile(
path.join(this.cachePath, item),
"utf8",
(err, cacheContents) => {
this.transport.send(cacheContents);
fs.unlink(path.join(this.cachePath, item), () => {});
},
);
}

init(offlineStorageOptions: OfflineStorageOptions | undefined) {
Expand All @@ -46,7 +47,7 @@ export class OfflineStorage implements IOfflineStorage {
this.cacheLimit = offlineStorageOptions.cacheLimit || 100;

debug(
`offline storage - initialized (cachePath=${this.cachePath}, cacheLimit=${this.cacheLimit}`
`offline storage - initialized (cachePath=${this.cachePath}, cacheLimit=${this.cacheLimit}`,
);

if (!fs.existsSync(this.cachePath)) {
Expand Down Expand Up @@ -86,7 +87,7 @@ export class OfflineStorage implements IOfflineStorage {
}

retrieve(
callback: (error: NodeJS.ErrnoException | null, items: string[]) => void
callback: (error: NodeJS.ErrnoException | null, items: string[]) => void,
) {
fs.readdir(this.cachePath, callback);
}
Expand All @@ -101,7 +102,7 @@ export class OfflineStorage implements IOfflineStorage {

if (items.length > 0) {
debug(
"offline storage - transporting ${items.length} message(s) from cache"
"offline storage - transporting ${items.length} message(s) from cache",
);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/raygun.sync.transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function send(options: SendOptionsWithoutCB) {
syncRequest(options);
} catch (e) {
console.log(
`Raygun: error ${e} occurred while attempting to send error with message: ${options.message}`
`Raygun: error ${e} occurred while attempting to send error with message: ${options.message}`,
);
}
}
2 changes: 1 addition & 1 deletion lib/raygun.sync.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function callback(error: Error | null, result: IncomingMessage | null) {
console.log("Error sending with sync transport", error);
} else {
console.log(
"[raygun-apm] Successfully reported uncaught exception to Raygun"
"[raygun-apm] Successfully reported uncaught exception to Raygun",
);
}
}
Loading

0 comments on commit 3def9b9

Please sign in to comment.