Skip to content

Commit

Permalink
Feat:支持添加多个商品 & 流程优化
Browse files Browse the repository at this point in the history
* 支持相同时间多个商品同时抢购
* 秒杀流程提前请求订单数据
* 添加单元测试
* 访问秒杀链接增加重试次数
* 修复商品已在购物车,返回却是false
  • Loading branch information
meooxx authored and xxxXXX95 committed Feb 2, 2021
1 parent c3db356 commit 1d1135b
Show file tree
Hide file tree
Showing 10 changed files with 4,099 additions and 237 deletions.
9 changes: 8 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,14 @@ exports.pool = [
// 2 forceKO: true/false
// true 则为强制使用秒杀流程(自己100%确定流程是秒杀时开启.常见商品maotai)
// false 的话自动判断流程
{ skuId: '100011621642', date: dd1, areaId: `2_2825_51936`, forceKO: false },
// 3 注意有的商品在开抢前几分钟, 才把对应流程标志暴露出来,
// 所以想要使用程序自动判断流程准确
// 最好在开抢前很近的时候开启脚本, 这样就不会误判抢购模式
// 后续会改进
{ skuId: '100011621642', date: dd1, areaId: `2_2825_51936` },
// 新增同一时间抢购多个商品
// 不同时间, 像这样多项就可以了
{ skuId: ['100011621642', '100011621643'], date: dd2, areaId: `2_2825_51936` },
];
// 设置要强制扫码登录(没搞懂使用场景的忽略此配置)
// 说明: 因为 x 东, 24小时就要重新登录, 防止运行时登录状态有效
Expand Down
68 changes: 68 additions & 0 deletions __tests__/jobs.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const fetch = require('node-fetch');
jest.mock('node-fetch');

const { isSkuInCart, helper } = require('../jobs');

describe('isSkuInCart', function () {
beforeEach(() => {});
test('isSkuInCart should works find', async function () {
fetch.mockImplementation(() =>
Promise.resolve({
headers: {
raw: () => {
return {};
},
},
json() {
return {
success: true,
resultData: {
cartInfo: {
vendors: [
{
sorted: [
{
item: {
Id: 1,
},
},
{
item: {
Id: 2,
},
},
{
items: [
{
item: {
Id: 3,
},
},
],
},
],
},
{
sorted: [
{
item: {
Id: 5,
},
},
],
},
],
},
},
};
},
})
);
const res1 = await isSkuInCart('1');
const res2 = await isSkuInCart('2');
const res3 = await isSkuInCart('3');
const res4 = await isSkuInCart('4');
const res5 = await isSkuInCart('5');
expect([res1, res2, res3, res4, res5]).toEqual([[], [], [], ['4'], []]);
});
});
84 changes: 52 additions & 32 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ try {
process.exit();
}

const { login, submitOrderProcess } = require('./jobs');
const {
login,
submitOrderProcess,
} = require('./jobs');
const { pool, forceLogin } = require('./tasks-pool');
const config = require('./config');
if (!config.eid || !config.fp) {
Expand All @@ -20,44 +23,61 @@ if (!config.eid || !config.fp) {
}

if (cluster.isWorker) {
cluster.worker.once('message', item => {
if (item.type === 'loginWork') {
console.log('progress.worker login', process.pid);
if (item.forceLogin) {
console.warn(
'已开启强制扫码登录, 如果接下里24小时内频繁重启, 重启最好关闭了'
);
}
login(item.forceLogin).then(() => {
// 登陆完成后通知主进程
// 派生任务进程
cluster.worker.send('loginReady');
});
} else {
const { date, skuId, areaId = config.areaId, forceKO = false } = item;
// 任务进程
console.log(
'progress.worker:',
process.pid,
'时间:',
item.date,
'sku',
item.skuId
const setupLoginWork = item => {
console.log('progress.worker:login', process.pid);
if (item.forceLogin) {
console.warn(
'已开启强制扫码登录, 如果接下里24小时内频繁重启, 重启最好关闭了'
);
submitOrderProcess(date, skuId, areaId, forceKO);
}
return login(item.forceLogin);
};
const setupWork = item => {
const { date, skuId, areaId = config.areaId, forceKO = false } = item;
// 任务进程
console.log(
'progress.worker:',
process.pid,
'时间:',
item.date,
'sku',
item.skuId
);
submitOrderProcess(date, skuId, areaId, forceKO);
};
process.on('unhandledRejection', (reason, promise) => {
console.log(reason);
});
cluster.worker.on('message', async job => {
if (job.type === 'login') {
await setupLoginWork(job);
cluster.worker.send({ doneWork: 'login' });
}
if (job.type === 'task') {
setupWork(job);
}
});
} else {
// 使用独立进程登陆
// forcelogin, 强制登陆一次
cluster.fork().send({ type: 'loginWork', forceLogin });
cluster.on('message', () => {
// 登陆完成后
for (i = 0; i < pool.length; i++) {
const item = pool[i];
cluster.fork().send(item);
cluster.fork().send({ type: 'login', forceLogin });
cluster.on('message', (_, message) => {
// 登陆流程
if (message.doneWork === 'login') {
// 登陆完成后
for (i = 0; i < pool.length; i++) {
const item = pool[i];
cluster.fork().send({ ...item, type: 'task' });
}
}
// fork 秒杀流程
if (message.doneWork === 'forkKO') {
for (i = 0; i < message.items.length; i++) {
const item = message.items[i];
cluster.fork().send({ ...item, type: 'task', forceKO: true });
}
}
});

console.log('main progress');
console.log('progress.master:', process.pid);
}
193 changes: 193 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/en/configuration.html
*/

module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,

// Stop running tests after `n` failures
// bail: 0,

// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/cg/wx167bw9429cjxp4j718vxtw0000gn/T/jest_dx",

// Automatically clear mock calls and instances between every test
// clearMocks: false,

// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,

// The directory where Jest should output its coverage files
coverageDirectory: "coverage",

// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],

// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,

// A path to a custom dependency extractor
// dependencyExtractor: undefined,

// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,

// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],

// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,

// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,

// A set of global variables that need to be available in all test environments
// globals: {},

// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",

// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],

// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],

// Activates notifications for test results
// notify: false,

// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",

// A preset that is used as a base for Jest's configuration
// preset: undefined,

// Run tests from one or more projects
// projects: undefined,

// Use this configuration option to add custom reporters to Jest
// reporters: undefined,

// Automatically reset mock state between every test
// resetMocks: false,

// Reset the module registry before running each individual test
// resetModules: false,

// A path to a custom resolver
// resolver: undefined,

// Automatically restore mock state between every test
// restoreMocks: false,

// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,

// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],

// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",

// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],

// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

// The test environment that will be used for testing
testEnvironment: "node",

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},

// Adds a location field to test results
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
testMatch: [
"**/__tests__/**/*.[jt]s?(x)",
],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],

// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],

// This option allows the use of a custom results processor
// testResultsProcessor: undefined,

// This option allows use of a custom test runner
// testRunner: "jasmine2",

// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",

// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",

// A map from regular expressions to paths to transformers
// transform: undefined,

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,

// Indicates whether each individual test should be reported during the run
// verbose: undefined,

// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],

// Whether to use watchman for file crawling
// watchman: true,
};
Loading

0 comments on commit 1d1135b

Please sign in to comment.