Currently, I have a Netsuite SuiteScript where I export saved searches to csv's. It runs but it's not reusable and I'd like to make it easier by just adding key-value pairs. I have to a lot of copy pasting and it's easy to forget to update to the latest iteration of the run. It's a scheduled search which means it runs every 15 minutes and makes it hard to debug and test.
Right now, my code looks like this, but with more searches, and it's a pain is not reusable.
/**
* #NApiVersion 2.x
* #NScriptType ScheduledScript
* #NModuleScope SameAccount
*/
define(['N/task'],
/**
* #param {record} record
* #param {search} search
*/
function(task) {
var FILE_ID = 2992639;
var SEARCH_ID = 2993;
function execute(scriptContext) {
//first search
var searchTask1 = task.create({
taskType: task.TaskType.SEARCH
});
searchTask1.savedSearchId = SEARCH_ID;
searchTask1.fileId = FILE_ID;
var searchTaskId1 = searchTask1.submit();
//next search
FILE_ID = 2992640;
SEARCH_ID = 3326;
var searchTask2 = task.create({
taskType: task.TaskType.SEARCH
});
searchTask2.savedSearchId = SEARCH_ID;
searchTask2.fileId = FILE_ID;
var searchTaskId2 = searchTask2.submit();
//next search
FILE_ID = 2992634;
SEARCH_ID = 3327;
var searchTask3 = task.create({
taskType: task.TaskType.SEARCH
});
searchTask3.savedSearchId = SEARCH_ID;
searchTask3.fileId = FILE_ID;
var searchTaskId3 = searchTask3.submit();
//this pattern repeats 19 times total.
}
return {
execute: execute
};
});
I've tried to code below
/**
* #NApiVersion 2.x
* #NScriptType ScheduledScript
* #NModuleScope SameAccount
*/
define(['N/task'],
/**
* #param {record} record
* #param {search} search
*/
function(task) {
const searchList = {
2993:2992639,
3326:2992640,
3327:2992634
};
function execute(scriptContext) {
for (const [key, value] of Object.entries(searchList)) {
var searchTask = task.create({
taskType: task.TaskType.SEARCH
});
searchTask.savedSearchId = $key;
searchTask.fileId = $value;
var searchTaskId = searchTask.submit();
}
}
return {
execute: execute
};
});
but get the following error, and I'm not sure what is wrong with my syntax. Netsuite makes it hard to tell what I'm doing wrong, so I'm hoping someone can help here. Thanks!
{"type":"error.SuiteScriptError","name":"SSS_MISSING_REQD_ARGUMENT","message":"task.submit: Missing a required argument: SearchTask.savedSearchId","stack":["createError(N/error)","execute(/SuiteScripts/dashboardreports.js:224)","createError(N/error)"],"cause":{"name":"SSS_MISSING_REQD_ARGUMENT","message":"task.submit: Missing a required argument: SearchTask.savedSearchId"},"id":"","notifyOff":false,"userFacing":true}
I would use a custom record to store the search and file IDs, so you can add/update without modifying code. Then I would do something like the code below. This code first queries your custom record to get all of the search and file ids, then for each one, starts a new task.
/**
* #NApiVersion 2.0
* #NScriptType ScheduledScript
* #NModuleScope Public
*/
define(['N/log', 'N/search', 'N/task'], function(log, search, task) {
function execute(context) {
var searchInfos = getSearchInfo();
searchInfos.forEach(function(searchInfo) {
var searchTask = task.create({
taskType: task.TaskType.SEARCH
});
searchTask.savedSearchId = searchInfo.searchId;
searchTask.fileId = searchInfo.fileId;
var searchTaskId = searchTask.submit();
log.debug({ title: 'searchTaskId', details: searchTaskId });
});
}
function getSearchInfo() {
var results = search.create({
type: 'customrecord_search_to_csv_info',
filters: [
['isinactive', 'is', 'F']
],
columns: [
'custcolumn_search_id',
'custcolumn_file_id'
]
}).run().getRange({ start: 0, end: 1000 });
return (results || []).map(function(result) {
return {
searchId: result.getValue({ name: 'custcolumn_search_id '}),
fileId: result.getValue({ name: 'custcolumn_file_id' })
}
});
}
return {
execute: execute
};
});
My Problem
I am trying to remove a specific item from my array, however, my array contains other objects which I cannot get a handle to.
I am defining a "Station" like this:
/* CLASS Station
* #param id int unique id this station
* #param name str name of the station
* #param location obj the position of the station
* in the workflow diagram
*/
var Station = function(id, name, posX=null, posY=null) {
this.id = ko.observable(id || self.getUniqueId());
this.name = ko.observable(name);
this.posX = ko.observable(posX);
this.posY = ko.observable(posY);
};
So I added a station to my array by using this function ...
.
.
self.addStation(new Station(76, "Receiving", 0, 10));
Now, I want to know how to remove from array by passing the name, as in:
self.removeStation("Receiving");
I can't figure it out. I have researched all the links on here, with no luck.
Entire Source Code
// CLASS Workflow
var Workflow = function(id, status){
this.status = status || false;
this.id = id;
}
/* CLASS Station
* #param id int unique id this station
* #param name str name of the station
* #param location obj the position of the station
* in the workflow diagram
*/
var Station = function(id, name, posX=null, posY=null) {
this.id = ko.observable(id || self.getUniqueId());
this.name = ko.observable(name);
this.posX = ko.observable(posX);
this.posY = ko.observable(posY);
};
// CLASS ViewModel
var ViewModel = function(workFlowId) {
var self = this; // Scope Trick
/*******************************
* Observables
*-----------------------------*/
self.station = ko.observableArray();
/*******************************
* Initialize The Builder
*-----------------------------*/
self.workflowId = ko.observable();
/*******************************
* Arrays
*-----------------------------*/
self.workflow = ko.observableArray();
/*******************************
* Actions
*-----------------------------*/
/* Method: initWorkflow
*
* Desc: When the user gets to the builder
* page, we have to configure a Workflow.
* If they are loading a saved one, the ID
* will be passed. If they are starting a new
* one, we will give it a unique ID.
*
* #param int workFlowId The id of the workflow
* #return int workFlowId The id is returned
*/
self.initWorkflow = function(workFlowId, status=false) {
var id;
if(!workFlowId){
/* Call Function to generate unique ID */
id = self.getUniqueId();
} else {
id = workFlowId;
}
/* Set ID */
this.workflowId = id;
this.workflow = new Workflow(id, status);
};
/*-------------------------------------------------------
* Method: addStation
*
* Desc: Adds a station to current workflow
* #param station object A station object
*--------------------------------------------------------*/
self.addStation = function(station){
self.station.push(station);
}
/* Remove Station - */
self.removeStation = function (Name) {
for( var i = 0; i < self.station().length; i++){
console.dir("In Remove Function: " + self.station()[i]);
}
}
/*-------------------------------------------------------
* Method: getUniqueId
*
* Desc: Generates a random unique Id
* #returns id int A unique random ID
*--------------------------------------------------------*/
self.getUniqueId = function(){
var id = new Date().getTime();
console.group("In Funtion: self.getUniqueId");
console.log("Returned unique id of: " + id);
console.groupEnd("In Funtion: self.getUniqueId");
return id;
}
/* Start it up */
self.initWorkflow(workFlowId);
//------------------------
// UNIT TESTING
//------------------------
//........ STATION RELATED ..........................
// 1. Add
self.addStation(new Station(76, "Receiving", 0, 10));
// 2. Remove
self.removeStation("Receiving");
} // end ViewModel
// Instantiate the ViewModel
window.view_model = new ViewModel();
// Away we go...
ko.applyBindings(window.view_model);
I can't seem to get a hold of the name in the array:
// DON'T WORK
self.station()[i].Station.name
Thanks for looking.
John
u could use function to find its index look like:
function arrayFirstIndexOf(array, predicate, predicateOwner) {
for (var i = 0, j = array.length; i < j; i++) {
if (predicate.call(predicateOwner, array[i])) {
return i;
}
}
return -1;
}
then in your /* Remove Station - */u edit code look like this:
/* Remove Station - */
self.removeStation = function (Name) {
var index = arrayFirstIndexOf(self.station(), function(item){
return item.name === Name;
});
index > -1 && self.station.splice(index, 1);
}
Hope this help !
you can use ko.utils.arrayRemoveItem to remove an item from the array you need to find it first
/* Remove Station */
self.removeStation = function (search) {
// find the station
var foundStation = ko.utils.arrayFirst(this.station, function(item) {
return ko.utils.stringStartsWith(item.name().toLowerCase(), search);
});
// remove the station
ko.utils.arrayRemoveItem(this.station, foundStation);
}
Thank you for your responses. But I found an acceptable solution to my problem by using this following code:
/* Remove Station */
self.removeStation = function (Name) {
var c = -1;
ko.utils.arrayForEach(this.station(), function(item) {
c++;
var value = item.name();
if(value==Name){
console.log("found it! at index " + c);
self.station().splice(c,1);
}
});
// Force the UI to update
self.station.valueHasMutated();
}
I realize this is not the cleanest or most efficient solution, but it seems to work. I would love to know how to optimize this, but that's above my pay grade, lol.
sry for long days answer, i think the problem you got is about variable you declared and variable you use not the same type, and you not use any convert of them when u assigned to your object look like:
var Station = function(id, name, posX=null, posY=null) {
this.id = ko.observable(id || self.getUniqueId()); //observalbe declared
this.name = ko.observable(name);//observalbe declared
this.posX = ko.observable(posX);//observalbe declared
this.posY = ko.observable(posY);//observalbe declared
};
but then you use assign look like
var newObj = {
id: "82",
name: "Updated Name",
posX: 92,
posY: 88
}
self.modifyStation("name","Shipping",newObj);
when u assign it:
objNewItem.id = oldId; // Put old ID back in
self.station.push(objNewItem); //not convert its properties to observable will make some errors on binding html.
i make a working jsfildle with your example, please read it, and reply when u not understand which part. hope this help.
function arrayFirstIndexOf(array, predicate, predicateOwner) {
for (var i = 0, j = array.length; i < j; i++) {
if (predicate.call(predicateOwner, array[i])) {
return i;
}
}
return -1;
}
// CLASS Workflow
var Workflow = function(id, status) {
this.status = status || false;
this.id = id;
}
/* CLASS Field
* #param id int unique id this station
* #param fieldType str type of input
* #param fieldName obj name of the input
* #param options array options array
*/
var Field = function(fieldId, fieldType, fieldName, options) {
this.fieldId = ko.observable(fieldId);
this.fieldType = ko.observable(fieldType);
this.fieldName = ko.observable(fieldName);
this.options = ko.observableArray(options);
};
/* CLASS Station
* #param id int unique id this station
* #param name str name of the station
* #param location obj the position of the station
* in the workflow diagram
*/
var Station = function(id, name, posX = null, posY = null, fields) {
this.id = ko.observable(id || self.getUniqueId());
this.name = ko.observable(name);
this.posX = ko.observable(posX);
this.posY = ko.observable(posY);
this.fields = ko.observableArray(fields || []);
};
// CLASS ViewModel
var ViewModel = function(workFlowId) {
var self = this; // Scope Trick
/*******************************
* Observables
*-----------------------------*/
self.fieldId = ko.observable();
self.fieldName = ko.observable();
self.fieldType = ko.observable();
/*******************************
* Initialize The Builder
*-----------------------------*/
self.workflowId = ko.observable();
/*******************************
* Arrays
*-----------------------------*/
self.workflow = ko.observableArray();
self.station = ko.observableArray();
self.fields = ko.observableArray();
/*******************************
* Computed Observables
*-----------------------------*/
/*******************************
* Actions
*-----------------------------*/
/* Method: initWorkflow
*
* Desc: When the user gets to the builder
* page, we have to configure a Workflow.
* If they are loading a saved one, the ID
* will be passed. If they are starting a new
* one, we will give it a unique ID.
*
* #param int workFlowId The id of the workflow
* #return int workFlowId The id is returned
*/
self.initWorkflow = function(workFlowId, status = false) {
var id;
if (!workFlowId) {
/* Call Function to generate unique ID */
id = self.getUniqueId();
} else {
id = workFlowId;
}
/* Set ID */
this.workflowId = id;
this.workflow = new Workflow(id, status);
};
/*-------------------------------------------------------
* Method: addStation
*
* Desc: Adds a station to current workflow
* #param station object A station object
*--------------------------------------------------------*/
self.addStation = function(station) {
self.station.push(station);
}
/* Remove Station */
self.removeStation = function(Name) {
var index = arrayFirstIndexOf(self.station(), function(item){
return item.name() === Name;
});
index > -1 && self.station.splice(index, 1);
}
/* Update A Station ** NEEDS FIXING **
*
* #param findBy string Property to find ( "id" or "name")
* #param cmpVal string Value to compare against
* #param objNewItem object The new object replacing old
* */
self.modifyStation = function(findBy, cmpVal, objNewItem) {
var sourceIndex;
var oldId;
var found = false;
/* Find Index Of Old Station */
var c = -1;
ko.utils.arrayForEach(this.station(), function(item) {
c++;
switch (findBy) {
case "id":
var value = ko.unwrap(item.id);
if (value == cmpVal) {
sourceIndex = c;
oldId = value;
found = true;
}
break;
case "name":
var value = ko.unwrap(item.name);
if (value == cmpVal) {
sourceIndex = c;
oldId = ko.unwrap(item.id);
found = true;
}
break;
}
});
/* Remove Old */
if (found === true) {
self.station().splice(sourceIndex, 1);
/* Insert New Station
* [For Now] not allowing updating of ID. Only
* can update the other properties (yes, I realize that
* only leaves "name", but more will be added )
*/
objNewItem.id(oldId); // Put old ID back in
self.station.push(objNewItem);
} else {
alert(cmpVal + " was not found in array!");
}
}
self.addField = function(stationId, newField) {
var c = -1;
found = false;
ko.utils.arrayForEach(this.station(), function(item) {
c++;
var value = ko.unwrap(item.id);
console.log(value, c);
if (value == stationId) {
//console.log("found it! at index " + c);
self.station()[c].fields.push(newField);
}
});
self.station.valueHasMutated();
};
self.modifyField = function(stationId, oldFieldId, newObjField) {
// TO DO
};
self.removeField = function(field) {
self.fields.remove(field);
};
/* Perform Test On Button Click */
self.doTest = function() {
self.removeStation("Shipping");
}
self.doTest2 = function() {
var newObj = {
id: ko.observable("82"),
name: ko.observable("Updated Name"),
posX: ko.observable(92),
posY: ko.observable(88),
fields: ko.observableArray([])
}
self.modifyStation("name", "Shipping", newObj);
self.station.valueHasMutated();
}
// Add Fields
self.doTest3 = function() {
var objNewField = {
fieldId: 456,
fieldName: "Last Name",
fieldType: "Text"
}
self.addField(86, objNewField);
}
/*-------------------------------------------------------
* Method: getUniqueId
*
* Desc: Generates a random unique Id
* #returns id int A unique random ID
*--------------------------------------------------------*/
self.getUniqueId = function() {
var id = new Date().getTime();
console.group("In Funtion: self.getUniqueId");
console.log("Returned unique id of: " + id);
console.groupEnd("In Funtion: self.getUniqueId");
return id;
}
/*-------------------------------------------------------
* Method: debugAll
*
* Desc: Console Logs Our View Model
*--------------------------------------------------------*/
this.debugAll = function() {
console.group("Debug:");
// Workflow
console.group("Current Workflow Id")
console.log("self.workflowId = " + self.workflowId);
console.groupEnd("Current Workflow Id")
// Stations
console.group("Stations In This Workflow")
console.table(self.station());
console.groupEnd("Stations In This Workflow")
// Fields
console.groupEnd("Debug:");
}
/* Start it up */
self.initWorkflow(workFlowId);
//------------------------
// UNIT TESTING
//------------------------
//........ STATION RELATED ..........................
// 1. Add
self.addStationShipping = function() {
self.addStation(new Station(86, "Shipping", 0, 10, [{
fieldId: 45,
fieldName: "First Name",
fieldType: "Text"
}]));
}
self.addStation(new Station(76, "Receiving", 0, 10, null));
self.addStationShipping();
/* Dump ViewModel */
self.debugAll();
//----------------------------------------------------------------
} // end ViewModel
// Instantiate the ViewModel
window.view_model = new ViewModel(1213131212);
// Away we go...
ko.applyBindings(window.view_model);
// Page Utility Functions
function wait(ms) {
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div>
<ul data-bind="foreach: station">
<li data-bind="text: 'id: ' + id()"></li>
<li data-bind="text: 'name: ' +name()"></li>
<li data-bind="text: 'posX: ' +posX()"></li>
<li data-bind="text: 'posY: ' +posY()"></li>
<ul data-bind="foreach: fields">
<li data-bind="text: fieldId"></li>
<li data-bind="text: fieldName"></li>
<li data-bind="text: fieldType"></li>
</ul>
</ul>
</div>
<button data-bind="click: doTest">Remove "Shipping" From Station Array</button>
<button data-bind="click: doTest2">Update "Shipping" In Station Array</button>
<hr>
<h3>Test: Add Field To Shipping Station</h3>
<button data-bind="click: function() { addStationShipping()}">Add Shpping</button>
<button data-bind="click: doTest3()">Add Field</button>
I would like to get the publicationdate from a URL, I can get it with the following code: window.dataLayer[0]['publicationdate'], but when it's time to make it work locally, the console gives me the following error "Cannot read property '0' of undefined". I have the following code, can someone please help me? Thank you!
"use strict";
var takashyx = takashyx || {};
takashyx.toast = (function() {
/**
* The main Toast object
* #param {Object} options See Toast.prototype.DEFAULT_SETTINGS for more info
*/
function Toast(text, options) {
if(getToastStage() != null) {
// If there is already a Toast being shown, hide it
Toast.prototype.destroy();
}
var _options = options || {};
_options = Toast.prototype.mergeOptions(Toast.prototype.DEFAULT_SETTINGS, _options);
Toast.prototype.show(text, _options);
_options = null;
};
/**
* The toastStage. This is the HTML element in which the toast resides
* Getter and setter methods are available privately
* #type {Element}
*/
var _toastStage = null;
function getToastStage() {
return _toastStage;
};
function setToastStage(toastStage) {
_toastStage = toastStage;
};
/**
* The Toast animation speed; how long the Toast takes to move to and from the screen
* #type {Number}
*/
Toast.prototype.TOAST_ANIMATION_SPEED = 400;
// Toast classes
Toast.prototype.CLASS_TOAST_GONE = "takashyx_toast_gone";
Toast.prototype.CLASS_TOAST_VISIBLE = "takashyx_toast_visible";
Toast.prototype.CLASS_TOAST_ANIMATED = "takashyx_toast_animated";
/**
* The default Toast settings
* #type {Object}
*/
Toast.prototype.DEFAULT_SETTINGS = {
style: {
main: {
"background": "rgba(0, 0, 0, .85)",
"box-shadow": "0 0 10px rgba(0, 0, 0, .8)",
"border-radius": "3px",
"z-index": "99999",
"color": "#01ff00",
"padding": "10px 15px",
"max-width": "40%",
"word-break": "keep-all",
"margin": "0 auto",
"text-align": "center",
"position": "fixed",
"left": "0",
"right": "0"
}
},
settings: {
duration: 4000
}
};
/**
* Specifies whether or not the inline style in the <head> exists. It only needs to be added once to a page
* #type {Boolean}
*/
Toast.prototype.styleExists = false;
/**
* The Timeout object for animations.
* This should be shared among the Toasts, because timeouts may be cancelled e.g. on explicit call of hide()
* #type {Object}
*/
Toast.prototype.timeout = null;
/**
* Merge the DEFAULT_SETTINGS with the user defined options if specified
* #param {Object} options The user defined options
*/
Toast.prototype.mergeOptions = function(initialOptions, customOptions) {
var merged = customOptions;
for(var prop in initialOptions) {
if(merged.hasOwnProperty(prop)) {
if(initialOptions[prop] != null && initialOptions[prop].constructor == Object) {
merged[prop] = Toast.prototype.mergeOptions(initialOptions[prop], merged[prop]);
}
} else {
merged[prop] = initialOptions[prop];
}
}
return merged;
};
/**
* Add the inline stylesheet to the <head>
* These inline styles are needed for animation purposes.
*/
Toast.prototype.initializeStyles = function() {
if(Toast.prototype.styleExists) return;
var style = document.createElement("style");
style.insertAdjacentHTML("beforeend",
Toast.prototype.generateInlineStylesheetRules(this.CLASS_TOAST_GONE, {
"opacity": "0",
"top": "10%"
}) +
Toast.prototype.generateInlineStylesheetRules(this.CLASS_TOAST_VISIBLE, {
"opacity": "1",
"top": "10%"
}) +
Toast.prototype.generateInlineStylesheetRules(this.CLASS_TOAST_ANIMATED, {
"transition": "opacity " + this.TOAST_ANIMATION_SPEED + "ms, bottom " + this.TOAST_ANIMATION_SPEED + "ms"
})
);
document.head.appendChild(style);
style = null;
// Notify that the stylesheet exists to avoid creating more
Toast.prototype.styleExists = true;
};
/**
* Generate the Toast with the specified text.
* #param {String|Object} text The text to show inside the Toast, can be an HTML element or plain text
* #param {Object} style The style to set for the Toast
*/
Toast.prototype.generate = function(text, style) {
var toastStage = document.createElement("div");
/**
* If the text is a String, create a textNode for appending
*/
if(typeof text === "string") {
var lines = text.split('[[[br]]]');
for (let i=0; i<lines.length; ++i) {
var l = document.createTextNode(lines[i]);
toastStage.appendChild(l);
var r = document.createElement('br');
toastStage.appendChild(r);
}
setToastStage(toastStage);
toastStage = null;
Toast.prototype.stylize(getToastStage(), style);
};
/**
* Stylize the Toast.
* #param {Element} element The HTML element to stylize
* #param {Object} styles An object containing the style to apply
* #return Returns nothing
*/
Toast.prototype.stylize = function(element, styles) {
Object.keys(styles).forEach(function(style) {
element.style[style] = styles[style];
console.log(style + ": "+ styles[style]);
});
};
/**
* Generates styles to be used in an inline stylesheet. The output will be something like:
* .class {background: blue;}
* #param {String} elementClass The class of the element to style
* #param {Object} styles The style to insert into the inline stylsheet
* #return {String} The inline style as a string
*/
Toast.prototype.generateInlineStylesheetRules = function(elementClass, styles) {
var out = "." + elementClass + "{";
Object.keys(styles).forEach(function(style) {
out += style + ":" + styles[style] + ";";
});
out += "}";
return out;
};
/**
* Show the Toast
* #param {String} text The text to show inside the Toast
* #param {Object} options The object containing the options for the Toast
*/
Toast.prototype.show = function(text, options) {
this.initializeStyles();
this.generate(text, options.style.main);
var toastStage = getToastStage();
toastStage.classList.add(this.CLASS_TOAST_ANIMATED);
toastStage.classList.add(this.CLASS_TOAST_GONE);
document.body.insertBefore(toastStage, document.body.firstChild);
// This is a hack to get animations started. Apparently without explicitly redrawing, it'll just attach the class and no animations would be done
toastStage.offsetHeight;
toastStage.classList.remove(this.CLASS_TOAST_GONE);
toastStage.classList.add(this.CLASS_TOAST_VISIBLE);
var toastStage = null;
clearTimeout(Toast.prototype.timeout);
Toast.prototype.timeout = setTimeout(Toast.prototype.hide, options.settings.duration);
};
/**
* Hide the Toast that's currently shown
*/
Toast.prototype.hide = function() {
var toastStage = getToastStage();
toastStage.classList.remove(Toast.prototype.CLASS_TOAST_VISIBLE);
toastStage.classList.add(Toast.prototype.CLASS_TOAST_GONE);
toastStage = null;
// Destroy the Toast element after animations end
clearTimeout(Toast.prototype.timeout);
Toast.prototype.timeout = setTimeout(Toast.prototype.destroy, Toast.prototype.TOAST_ANIMATION_SPEED);
};
/**
* Clean up after the Toast slides away. Namely, removing the Toast from the DOM.
*/
Toast.prototype.destroy = function() {
var toastStage = getToastStage();
document.body.removeChild(toastStage);
toastStage = null;
setToastStage(null);
};
return {
Toast: Toast
};
})();
Using OpenPGP.js v1.3.0 I can successfully create a public/private key pair and encrypt/decrypt ok.
I am struggling to obtain the key id using this function (found in openpgp.js and public_key.js):
/**
* Calculates the key id of the key
* #return {String} A 8 byte key id
*/
PublicKey.prototype.getKeyId = function () {
if (this.keyid) {
return this.keyid;
}
this.keyid = new type_keyid();
if (this.version == 4) {
this.keyid.read(util.hex2bin(this.getFingerprint()).substr(12, 8));
} else if (this.version == 3) {
this.keyid.read(this.mpi[0].write().substr(-8));
}
return this.keyid;
};
PublicKey() also in openpgp.js:
/**
* #constructor
*/
function PublicKey() {
this.tag = enums.packet.publicKey;
this.version = 4;
/** Key creation date.
* #type {Date} */
this.created = new Date();
/** A list of multiprecision integers
* #type {module:type/mpi} */
this.mpi = [];
/** Public key algorithm
* #type {module:enums.publicKey} */
this.algorithm = 'rsa_sign';
// time in days (V3 only)
this.expirationTimeV3 = 0;
/**
* Fingerprint in lowercase hex
* #type {String}
*/
this.fingerprint = null;
/**
* Keyid
* #type {module:type/keyid}
*/
this.keyid = null;
}
and trying to get the key id like this:
var publickey = openpgp.key.readArmored(myPublicKey);
//var keyID = openpgp.packet.PublicKey(publickey).getKeyId()[0].toHex();
var keyID = openpgp.PublicKey(publickey).getKeyId()[0].toHex();
console.log(keyID);
which gives me the error:
TypeError: openpgp.PublicKey is not a function.
Thanks.
I asked the question here:
http://www.mail-archive.com/list#openpgpjs.org/msg00932.html
and received a very helpful reply.
var openpgp = window.openpgp;
var testPublicKey = sessionStorage.getItem('testPublicKey');
var foundKeys = openpgp.key.readArmored(testPublicKey).keys;
if (!foundKeys || foundKeys.length !== 1) {
throw new Error("Key not read, or more than one key found");
}
var pubKey = foundKeys[0]; foundKeys = null;
var getFingerprint = function (key) {
// openpgp.key <- Class
// key <- Instance received by params
return key.primaryKey.fingerprint;
};
var getKeyId = function (key) {
return key.primaryKey.getKeyId().toHex();
}
console.log(getFingerprint(pubKey));
console.log(getKeyId(pubKey));