snowflakify
Version:
The most complete Snowflake ID generator in TypeScript
81 lines (80 loc) • 2.4 kB
JavaScript
;
var __importDefault =
(this && this.__importDefault) ||
function (mod) {
return mod && mod.__esModule ? mod : { default: mod };
};
Object.defineProperty(exports, '__esModule', { value: true });
const FragmentBase_js_1 = __importDefault(require('../FragmentBase.js'));
const Util_js_1 = require('../Utils/Util.js');
/**
* NetworkFragment class for network IDs.
* @public
*/
class NetworkFragment extends FragmentBase_js_1.default {
/**
* @param bits - The number of bits for the fragment.
* @param networkAddress - The type of network address to use, `"ipv4"` or `"mac"`.
*
* Defaults to `"ipv4"` if omitted.
*
* @throws `[NETWORK_ADDRESS_INVALID]` If networkAddress is not "ipv4" or "mac".
*/
constructor(bits, networkAddress = 'ipv4') {
super(bits);
this.networkAddress = networkAddress;
if (networkAddress !== 'ipv4' && networkAddress !== 'mac')
throw new Error(
`[NETWORK_ADDRESS_INVALID]: NetworkFragment networkAddress "${networkAddress}" is invalid; Expected "ipv4" or "mac".`,
);
this.value = this.getNetworkId();
}
getValue() {
return this.value;
}
destructure(snowflake) {
const bits = BigInt(snowflake) & this.bitMask;
return {
identifier: `${this.identifier}:${this.networkAddress}`,
value: Number(bits >> this.bitShift),
};
}
updateId() {
this.value = this.getNetworkId();
}
/**
* Returns the network ID.
*
* @remarks
* The value is masked by the maxValue to fit in the fragment's bits.
*
* @returns The network ID of the machine based on a non internal network address.
* @internal
*/
getNetworkId() {
let address = null;
if (this.networkAddress === 'ipv4') {
address = (0, Util_js_1.getIPv4Address)((err, ip) => {
if (err) {
throw err;
}
return ip;
});
} else {
address = (0, Util_js_1.getMacAddress)((err, mac) => {
if (err) {
throw err;
}
return mac;
});
}
const seperator = this.networkAddress === 'ipv4' ? '.' : ':';
const addressBinary =
address
?.split(seperator)
.reduce((acc, part) => acc.concat(Number(part).toString(2)), '') ?? '';
return BigInt(parseInt(addressBinary, 2)) & this.maxValue;
}
}
exports.default = NetworkFragment;
//# sourceMappingURL=NetworkFragment.js.map