How to Set a Series of setHeader's DRY - javascript

I'm just learning to use the DRY principle and I can't figure how to set a series of setHeader's DRY (if at all possible??).
Any help is appreciated.
function plugin(options) {
var defaults = {
cache: 0
, port: 8080
, host: 'localhost'
, verbose: false
, serverInfo: 'myserver'
, cacheControl: 'no-store'
, xPowerBy: 'Locomotion'
, xFrameOptions: 'DENY'
, xXSSProtection: '1; mode=block'
, xContentTypeOption: 'nosniff'
, contentSecurityPolicy: 'default-src "self"'
};
var opts = options || {};
setDefaults(opts, defaults);
return function(files, staticsmith, done) {
if (server) {
done();
return;
}
// Some stuff
server = require('http').createServer(function (request, response) {
response.setHeader('X-Powered-By', opts.xPowerBy);
response.setHeader('x-frame-options', opts.xFrameOptions);
response.setHeader('X-XSS-Protection', opts.xXSSProtection);
response.setHeader('X-Content-Type-Options', opts.xContentTypeOption);
response.setHeader('Cache-Control', opts.cacheControl);
response.setHeader('Content-Security-Policy', opts.contentSecurityPolicy);
// Does some more stuff
};
}

This isn't a major/offensive violation of the DRY principal because you are setting the header for different options/values each time.
Checking the documentation, it doesn't seem there is an overload that accepts an array of objects or objects with multiple header properties.
However, if you want to improve the code visually(and completely remove duplication), you can take a 'data-driven' approach and use an array
var headers = [{
name: 'X-Powered-By',
option: opts.xPowerBy
}, {
name: 'x-frame-options',
option: opts.xFrameOptions
}, {
name: 'X-XSS-Protection',
option: opts.xXSSProtection
}, {
name: 'X-Content-Type-Options',
option: opts.xContentTypeOption
}, {
name: 'Cache-Control',
option: opts.cacheControl
}, {
name: 'Content-Security-Policy',
option: opts.contentSecurityPolicy
}];
and then loop
for(var i = 0; i < headers.length; i++){
response.setHeader(headers[i].name, headers[i].option);
}

Related

Patch request to COSMOS DB: 404 not found

Updated: Solved by Sajeetharan's suggestion! Thanks.
I'm trying to implement the api to partially update cosmos db. I got 404 not found when I tested this patch request. I tested query in cosmo's db, it's working as expected. I don't know which part is wrong.
You should invoke the Patch on the container as how you have done fetchAll request.
Here is a sample,
const multipleOperations: PatchOperation[] = [
{
op: "add",
path: "/aka",
value: "MeFamily"
},
{
op: "replace",
path: "/lastName",
value: "Jose"
},
{
op: "remove",
path: "/parents"
},
{
op: "set",
path: "/address/zip",
value: 90211
},
{
op: "incr",
path: "/address/zip",
value: 5
}
];
const { resource: patchSource2 } = await container.item(patchId!).patch(multipleOperations);

How can i export variable to other files using nodejs?

I am new to nodejs i just want to bring data from event.js to app.js its in same directory but i could not get it working any idea how to make it work ?
app.js
var SnmpData = require('./event.js');
console.log('SNMP data',SnmpData);
event.js
var message = {
event: {
header: {
eventSource: "d-sms"
},
body: {
data: [
{
oid: "1.3.6.1.4.140.625",
host: "135.89.157.201",
port: "162",
value: "Problem with monitoring device",
type: ""
},
{
oid: "1.3.6.1.4.345.765",
host: "135.89.157.299",
port: "162",
value: "Problem with monitoring device-2",
type: ""
}],
message: "Activate Collaborate"
}
}
}
}
just add in the end of events.js this :
exports.message = message ;
Also take a look to node modules to understand how things work.

Extjs6 apply property from config via function

I used to write this in extjs4:
Ext.define('Superstore', {
extends: 'Ext.data.Store'
config : {
customer : null,
},
applyCustomer : function (value) {
this.customer = value;
},
model : 'Supermodel'
});
I tried the same in extjs6, but with no success:ยด
Ext.define('Supermodel', {
extend: 'Ext.data.Model',
requires: ['Ext.data.reader.Json', 'Ext.data.proxy.Rest'],
config: {
customer: null
},
fields: [
{name: 'id', type: 'string'},
...
],
proxy: {
type: 'rest',
url: '/customers/{customer}/users',
reader: {
type: 'json'
}
},
applyCustomer: function (value) {
this.customer = value;
this.proxy.url.replace('{customer}', value);
}
});
Did they remove the magic?
Or is there any other, better, way to build my url like in my code?
I've already seen a few solutions, but none of them fitted to my application.
I get the customerId via session which is sent by the backend after login. I would get the store via StoreManager, get the customer record and apply it to the proxy.
Thanks in advance.
If you don't need to manipulate the value use the update function instead:
updateCustomer: function(newValue){
this.proxy.url.replace('{customer}', newValue);
}
(And remove the applyCustomer function)

Name of Azure blob/filename when uploading

When I upload to azure container the filename that is saved is the uuid(guid) how can I change that?
I create the signatur by using the querystring "bloburi" added in the signature request.
$("#fine-uploader").fineUploaderAzure({
autoUpload : true,
debug: true,
validation: {
itemLimit: 10,
sizeLimit: 209715200 // 200 mb
},
resume: {
enabled: true,
id: 'ResumeUpload',
cookiesExpireIn: 7
},
extraButtons: {
folders: true
},
deleteFile: {
enabled: true
},
request: {
endpoint: 'https://xxx.blob.core.windows.net/'
},
cors: {
//all requests are expected to be cross-domain requests
expected: true,
//if you want cookies to be sent along with the request
sendCredentials: true
},
signature: {
endpoint: '/sig/'
},
uploadSuccess: {
endpoint: '/success'
}
});
The docs are wrong.
For version 4.4.0 the correct property to set is:blobProperties
// 'uuid', 'filename', or a function which may be promissory
blobProperties: {
name: "uuid"
},
I know this is an old question, but I ran into the same problem. You'll need to pass a Promise to get it to work:
name: function (id) {
return new Promise(function (resolve) {
resolve("The String You Want to Pass");
});
}
The default value for the name option is 'uuid' which will set the filename in Azure to the uuid. You can instead set it to 'filename' to have the object stored under the filename, or provide a function that will create some other name.
blobProperties: {
name: 'filename'
}
From my experience, the best method for generating filenames is to save the filename under a unique id subfolder. This guarantees that you save the original filename, and that there are no naming collisions.
blobProperties: {
name: function(id) {
var uuid = this.getUuid(id),
filename = this.getName(id);
return uuid + '/' + filename;
}
}

ExtJS store/proxy doesn't send delete method to server

I'm trying to create simple ExtJs application that manages Users and User's Roles. Set of REST services provide this functionality on back end.
When I assign a new Role to a User, appropriate data store sends POST (create) requests to the service. However when I remove existing Role from a User, it's removed only from store locally without sending DELETE request to the service.
Here is my code:
Model:
Ext.define('UserRole', {
extend: 'Ext.data.Model',
fields: [
{ name: 'Id', mapping: "Id" },
{ name: 'RoleId', mapping: "RoleId" },
{ name: 'UserId', mapping: "UserId" }
]
});
Store With proxy:
Ext.define('UserRoleStore', {
extend: 'Ext.data.Store',
model: 'UserRole',
autoload: false,
proxy: {
type: 'ajax',
reader: {
type: 'json',
root: 'd.results'
},
api: {
read: '/accessmanager.svc/Users(\'{userid}\')/Roles?$format=json',
create: '/accessmanager.svc/UserRoles?$format=json',
update: '/accessmanager.svc/UserRoles?$format=json',
destroy: '/accessmanager.svc/UserRoles?$format=json'
},
updateApiUrlWithUserId: function (userId) {
this.api.read = this.api.read.replace('{userid}', userId);
}
}
});
Method that based on selected checkboxes updates the UserRole store
var chekboxes = Ext.ComponentQuery.query('userdetails #roleslist')[0];
var selectedUserId = this.selectedUserId;
var selectedUserRoleStore = this.selectedUserRoleStore;
Ext.each(chekboxes.items.items, function (cb) {
var exists = false;
Ext.each(selectedUserRoleStore.data.items, function (cs) {
if (cs.data.RoleId === cb.inputValue) {
exists = true;
}
});
if (cb.getValue() && !exists) {
var newRole = Ext.create('UserRole', { RoleId: cb.inputValue, UserId: selectedUserId });
selectedUserRoleStore.add(newRole);
} else if (exists && !cb.getValue()) {
// delete existing role
var record = selectedUserRoleStore.findRecord("RoleId", cb.inputValue);
selectedUserRoleStore.remove(record);
}
});
selectedUserRoleStore.sync();
Presumably your Id field is assigned on the server end when record is created. Correct? First try to specify idProperty: 'Id' in the model. Default value for this is 'id' but I think these are case sensitive.
Using idProperty ExtJs recognizes records as being 'dirty' and required to be updated on the server end.
The issue is your proxy needs to be a specialized REST type:
proxy: {
type: 'rest',
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.proxy.Rest
Also, you will probably be able to use the buildURL method to replace your own updateAPI... method.

Categories

Resources