[backend] fix: 修复异常处理和类型转换问题

This commit is contained in:
xsl
2026-01-26 11:53:40 +08:00
parent 7ccc2a6ac6
commit 83e05bf85f
28639 changed files with 2506458 additions and 93 deletions
+196
View File
@@ -0,0 +1,196 @@
# gensync
This module allows for developers to write common code that can share
implementation details, hiding whether an underlying request happens
synchronously or asynchronously. This is in contrast with many current Node
APIs which explicitly implement the same API twice, once with calls to
synchronous functions, and once with asynchronous functions.
Take for example `fs.readFile` and `fs.readFileSync`, if you're writing an API
that loads a file and then performs a synchronous operation on the data, it
can be frustrating to maintain two parallel functions.
## Example
```js
const fs = require("fs");
const gensync = require("gensync");
const readFile = gensync({
sync: fs.readFileSync,
errback: fs.readFile,
});
const myOperation = gensync(function* (filename) {
const code = yield* readFile(filename, "utf8");
return "// some custom prefix\n" + code;
});
// Load and add the prefix synchronously:
const result = myOperation.sync("./some-file.js");
// Load and add the prefix asynchronously with promises:
myOperation.async("./some-file.js").then(result => {
});
// Load and add the prefix asynchronously with promises:
myOperation.errback("./some-file.js", (err, result) => {
});
```
This could even be exposed as your official API by doing
```js
// Using the common 'Sync' suffix for sync functions, and 'Async' suffix for
// promise-returning versions.
exports.myOperationSync = myOperation.sync;
exports.myOperationAsync = myOperation.async;
exports.myOperation = myOperation.errback;
```
or potentially expose one of the async versions as the default, with a
`.sync` property on the function to expose the synchronous version.
```js
module.exports = myOperation.errback;
module.exports.sync = myOperation.sync;
````
## API
### gensync(generatorFnOrOptions)
Returns a function that can be "await"-ed in another `gensync` generator
function, or executed via
* `.sync(...args)` - Returns the computed value, or throws.
* `.async(...args)` - Returns a promise for the computed value.
* `.errback(...args, (err, result) => {})` - Calls the callback with the computed value, or error.
#### Passed a generator
Wraps the generator to populate the `.sync`/`.async`/`.errback` helpers above to
allow for evaluation of the generator for the final value.
##### Example
```js
const readFile = function* () {
return 42;
};
const readFileAndMore = gensync(function* (){
const val = yield* readFile();
return 42 + val;
});
// In general cases
const code = readFileAndMore.sync("./file.js", "utf8");
readFileAndMore.async("./file.js", "utf8").then(code => {})
readFileAndMore.errback("./file.js", "utf8", (err, code) => {});
// In a generator being called indirectly with .sync/.async/.errback
const code = yield* readFileAndMore("./file.js", "utf8");
```
#### Passed an options object
* `opts.sync`
Example: `(...args) => 4`
A function that will be called when `.sync()` is called on the `gensync()`
result, or when the result is passed to `yield*` in another generator that
is being run synchronously.
Also called for `.async()` calls if no async handlers are provided.
* `opts.async`
Example: `async (...args) => 4`
A function that will be called when `.async()` or `.errback()` is called on
the `gensync()` result, or when the result is passed to `yield*` in another
generator that is being run asynchronously.
* `opts.errback`
Example: `(...args, cb) => cb(null, 4)`
A function that will be called when `.async()` or `.errback()` is called on
the `gensync()` result, or when the result is passed to `yield*` in another
generator that is being run asynchronously.
This option allows for simpler compatibility with many existing Node APIs,
and also avoids introducing the extra even loop turns that promises introduce
to access the result value.
* `opts.name`
Example: `"readFile"`
A string name to apply to the returned function. If no value is provided,
the name of `errback`/`async`/`sync` functions will be used, with any
`Sync` or `Async` suffix stripped off. If the callback is simply named
with ES6 inference (same name as the options property), the name is ignored.
* `opts.arity`
Example: `4`
A number for the length to set on the returned function. If no value
is provided, the length will be carried over from the `sync` function's
`length` value.
##### Example
```js
const readFile = gensync({
sync: fs.readFileSync,
errback: fs.readFile,
});
const code = readFile.sync("./file.js", "utf8");
readFile.async("./file.js", "utf8").then(code => {})
readFile.errback("./file.js", "utf8", (err, code) => {});
```
### gensync.all(iterable)
`Promise.all`-like combinator that works with an iterable of generator objects
that could be passed to `yield*` within a gensync generator.
#### Example
```js
const loadFiles = gensync(function* () {
return yield* gensync.all([
readFile("./one.js"),
readFile("./two.js"),
readFile("./three.js"),
]);
});
```
### gensync.race(iterable)
`Promise.race`-like combinator that works with an iterable of generator objects
that could be passed to `yield*` within a gensync generator.
#### Example
```js
const loadFiles = gensync(function* () {
return yield* gensync.race([
readFile("./one.js"),
readFile("./two.js"),
readFile("./three.js"),
]);
});
```
+37
View File
@@ -0,0 +1,37 @@
{
"name": "gensync",
"version": "1.0.0-beta.2",
"license": "MIT",
"description": "Allows users to use generators in order to write common functions that can be both sync or async.",
"main": "index.js",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://github.com/loganfsmyth/gensync",
"repository": {
"type": "git",
"url": "https://github.com/loganfsmyth/gensync.git"
},
"scripts": {
"test": "jest"
},
"engines": {
"node": ">=6.9.0"
},
"keywords": [
"async",
"sync",
"generators",
"async-await",
"callbacks"
],
"devDependencies": {
"babel-core": "^6.26.3",
"babel-preset-env": "^1.6.1",
"eslint": "^4.19.1",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-node": "^6.0.1",
"eslint-plugin-prettier": "^2.6.0",
"flow-bin": "^0.71.0",
"jest": "^22.4.3",
"prettier": "^1.12.1"
}
}
+489
View File
@@ -0,0 +1,489 @@
"use strict";
const promisify = require("util.promisify");
const gensync = require("../");
const TEST_ERROR = new Error("TEST_ERROR");
const DID_ERROR = new Error("DID_ERROR");
const doSuccess = gensync({
sync: () => 42,
async: () => Promise.resolve(42),
});
const doError = gensync({
sync: () => {
throw DID_ERROR;
},
async: () => Promise.reject(DID_ERROR),
});
function throwTestError() {
throw TEST_ERROR;
}
async function expectResult(
fn,
arg,
{ error, value, expectSync = false, syncErrback = expectSync }
) {
if (!expectSync) {
expect(() => fn.sync(arg)).toThrow(TEST_ERROR);
} else if (error) {
expect(() => fn.sync(arg)).toThrow(error);
} else {
expect(fn.sync(arg)).toBe(value);
}
if (error) {
await expect(fn.async(arg)).rejects.toBe(error);
} else {
await expect(fn.async(arg)).resolves.toBe(value);
}
await new Promise((resolve, reject) => {
let sync = true;
fn.errback(arg, (err, val) => {
try {
expect(err).toBe(error);
expect(val).toBe(value);
expect(sync).toBe(syncErrback);
resolve();
} catch (e) {
reject(e);
}
});
sync = false;
});
}
describe("gensync({})", () => {
describe("option validation", () => {
test("disallow async and errback handler together", () => {
try {
gensync({
sync: throwTestError,
async: throwTestError,
errback: throwTestError,
});
throwTestError();
} catch (err) {
expect(err.message).toMatch(
/Expected one of either opts.async or opts.errback, but got _both_\./
);
expect(err.code).toBe("GENSYNC_OPTIONS_ERROR");
}
});
test("disallow missing sync handler", () => {
try {
gensync({
async: throwTestError,
});
throwTestError();
} catch (err) {
expect(err.message).toMatch(/Expected opts.sync to be a function./);
expect(err.code).toBe("GENSYNC_OPTIONS_ERROR");
}
});
test("errback callback required", () => {
const fn = gensync({
sync: throwTestError,
async: throwTestError,
});
try {
fn.errback();
throwTestError();
} catch (err) {
expect(err.message).toMatch(/function called without callback/);
expect(err.code).toBe("GENSYNC_ERRBACK_NO_CALLBACK");
}
});
});
describe("generator function metadata", () => {
test("automatic naming", () => {
expect(
gensync({
sync: function readFileSync() {},
async: () => {},
}).name
).toBe("readFile");
expect(
gensync({
sync: function readFile() {},
async: () => {},
}).name
).toBe("readFile");
expect(
gensync({
sync: function readFileAsync() {},
async: () => {},
}).name
).toBe("readFileAsync");
expect(
gensync({
sync: () => {},
async: function readFileSync() {},
}).name
).toBe("readFileSync");
expect(
gensync({
sync: () => {},
async: function readFile() {},
}).name
).toBe("readFile");
expect(
gensync({
sync: () => {},
async: function readFileAsync() {},
}).name
).toBe("readFile");
expect(
gensync({
sync: () => {},
errback: function readFileSync() {},
}).name
).toBe("readFileSync");
expect(
gensync({
sync: () => {},
errback: function readFile() {},
}).name
).toBe("readFile");
expect(
gensync({
sync: () => {},
errback: function readFileAsync() {},
}).name
).toBe("readFileAsync");
});
test("explicit naming", () => {
expect(
gensync({
name: "readFile",
sync: () => {},
async: () => {},
}).name
).toBe("readFile");
});
test("default arity", () => {
expect(
gensync({
sync: function(a, b, c, d, e, f, g) {
throwTestError();
},
async: throwTestError,
}).length
).toBe(7);
});
test("explicit arity", () => {
expect(
gensync({
arity: 3,
sync: throwTestError,
async: throwTestError,
}).length
).toBe(3);
});
});
describe("'sync' handler", async () => {
test("success", async () => {
const fn = gensync({
sync: (...args) => JSON.stringify(args),
});
await expectResult(fn, 42, { value: "[42]", expectSync: true });
});
test("failure", async () => {
const fn = gensync({
sync: (...args) => {
throw JSON.stringify(args);
},
});
await expectResult(fn, 42, { error: "[42]", expectSync: true });
});
});
describe("'async' handler", async () => {
test("success", async () => {
const fn = gensync({
sync: throwTestError,
async: (...args) => Promise.resolve(JSON.stringify(args)),
});
await expectResult(fn, 42, { value: "[42]" });
});
test("failure", async () => {
const fn = gensync({
sync: throwTestError,
async: (...args) => Promise.reject(JSON.stringify(args)),
});
await expectResult(fn, 42, { error: "[42]" });
});
});
describe("'errback' sync handler", async () => {
test("success", async () => {
const fn = gensync({
sync: throwTestError,
errback: (...args) => args.pop()(null, JSON.stringify(args)),
});
await expectResult(fn, 42, { value: "[42]", syncErrback: true });
});
test("failure", async () => {
const fn = gensync({
sync: throwTestError,
errback: (...args) => args.pop()(JSON.stringify(args)),
});
await expectResult(fn, 42, { error: "[42]", syncErrback: true });
});
});
describe("'errback' async handler", async () => {
test("success", async () => {
const fn = gensync({
sync: throwTestError,
errback: (...args) =>
process.nextTick(() => args.pop()(null, JSON.stringify(args))),
});
await expectResult(fn, 42, { value: "[42]" });
});
test("failure", async () => {
const fn = gensync({
sync: throwTestError,
errback: (...args) =>
process.nextTick(() => args.pop()(JSON.stringify(args))),
});
await expectResult(fn, 42, { error: "[42]" });
});
});
});
describe("gensync(function* () {})", () => {
test("sync throw before body", async () => {
const fn = gensync(function*(arg = throwTestError()) {});
await expectResult(fn, undefined, {
error: TEST_ERROR,
syncErrback: true,
});
});
test("sync throw inside body", async () => {
const fn = gensync(function*() {
throwTestError();
});
await expectResult(fn, undefined, {
error: TEST_ERROR,
syncErrback: true,
});
});
test("async throw inside body", async () => {
const fn = gensync(function*() {
const val = yield* doSuccess();
throwTestError();
});
await expectResult(fn, undefined, {
error: TEST_ERROR,
});
});
test("error inside body", async () => {
const fn = gensync(function*() {
yield* doError();
});
await expectResult(fn, undefined, {
error: DID_ERROR,
expectSync: true,
syncErrback: false,
});
});
test("successful return value", async () => {
const fn = gensync(function*() {
const value = yield* doSuccess();
expect(value).toBe(42);
return 84;
});
await expectResult(fn, undefined, {
value: 84,
expectSync: true,
syncErrback: false,
});
});
test("successful final value", async () => {
const fn = gensync(function*() {
return 42;
});
await expectResult(fn, undefined, {
value: 42,
expectSync: true,
});
});
test("yield unexpected object", async () => {
const fn = gensync(function*() {
yield {};
});
try {
await fn.async();
throwTestError();
} catch (err) {
expect(err.message).toMatch(
/Got unexpected yielded value in gensync generator/
);
expect(err.code).toBe("GENSYNC_EXPECTED_START");
}
});
test("yield suspend yield", async () => {
const fn = gensync(function*() {
yield Symbol.for("gensync:v1:start");
// Should be "yield*" for no error.
yield {};
});
try {
await fn.async();
throwTestError();
} catch (err) {
expect(err.message).toMatch(/Expected GENSYNC_SUSPEND, got {}/);
expect(err.code).toBe("GENSYNC_EXPECTED_SUSPEND");
}
});
test("yield suspend return", async () => {
const fn = gensync(function*() {
yield Symbol.for("gensync:v1:start");
// Should be "yield*" for no error.
return {};
});
try {
await fn.async();
throwTestError();
} catch (err) {
expect(err.message).toMatch(/Unexpected generator completion/);
expect(err.code).toBe("GENSYNC_EXPECTED_SUSPEND");
}
});
});
describe("gensync.all()", () => {
test("success", async () => {
const fn = gensync(function*() {
const result = yield* gensync.all([doSuccess(), doSuccess()]);
expect(result).toEqual([42, 42]);
});
await expectResult(fn, undefined, {
value: undefined,
expectSync: true,
syncErrback: false,
});
});
test("error first", async () => {
const fn = gensync(function*() {
yield* gensync.all([doError(), doSuccess()]);
});
await expectResult(fn, undefined, {
error: DID_ERROR,
expectSync: true,
syncErrback: false,
});
});
test("error last", async () => {
const fn = gensync(function*() {
yield* gensync.all([doSuccess(), doError()]);
});
await expectResult(fn, undefined, {
error: DID_ERROR,
expectSync: true,
syncErrback: false,
});
});
test("empty list", async () => {
const fn = gensync(function*() {
yield* gensync.all([]);
});
await expectResult(fn, undefined, {
value: undefined,
expectSync: true,
syncErrback: false,
});
});
});
describe("gensync.race()", () => {
test("success", async () => {
const fn = gensync(function*() {
const result = yield* gensync.race([doSuccess(), doError()]);
expect(result).toEqual(42);
});
await expectResult(fn, undefined, {
value: undefined,
expectSync: true,
syncErrback: false,
});
});
test("error", async () => {
const fn = gensync(function*() {
yield* gensync.race([doError(), doSuccess()]);
});
await expectResult(fn, undefined, {
error: DID_ERROR,
expectSync: true,
syncErrback: false,
});
});
});