Swagger codegen - swift 3 ignore params - swift3

There is a problem with header params in Swagger Codegen. my RAML file looks like that :
---...---
parameters:
timeParam_begin:
in: header
name: timeframe_begin
type: string
timeParam_end:
name: timeframe_end
in: header
type: string
recommendationsParam:
name: recommendations
in: header
default: 3
type: number
--- ....----
and later
---...----
post:
summary: Search for possible coordinates given an address
parameters:
- $ref: '#/parameters/timeParam_begin'
- $ref: '#/parameters/timeParam_end'
- $ref: '#/parameters/recommendationsParam'
---...----
Until here EVERYTHING IS GOOD, the validation is ok and the parameters works well.
But...
when I export it in swift (1,2 or3) there is a problem :
/**
- POST /tasks
- Add 'Task' object.
- examples: [{contentType=application/json, example="Task added succesfully"}]
- parameter task: (body) task object
- returns: RequestBuilder<String>
*/
open class func tasksPostWithRequestBuilder(task: Task) -> RequestBuilder<String> {
let path = "/tasks"
let URLString = SwaggerClientAPI.basePath + path
let parameters = task.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<String>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
No more headers parameters !
I try to export it in PHP and typescript, the parameters are here !!!!! :
Typescript Angular2 :
/**
*
* Add 'Task' object.
* #param task task object
* #param timeframeBegin
* #param timeframeEnd
* #param recommendations
*/
public tasksPostWithHttpInfo(task: models.Task, timeframeBegin?: string, timeframeEnd?: string, recommendations?: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + `/tasks`;
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'task' is not null or undefined
if (task === null || task === undefined) {
throw new Error('Required parameter task was null or undefined when calling tasksPost.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
'application/x-www-form-urlencoded'
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: task == null ? '' : JSON.stringify(task), // https://github.com/angular/angular/issues/10612
search: queryParameters
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = this.extendObj(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
PHP :
/**
* Operation tasksPostWithHttpInfo
*
*
*
* #param \Swagger\Client\Model\Task $task task object (required)
* #param string $timeframe_begin (optional)
* #param string $timeframe_end (optional)
* #param float $recommendations (optional, default to 3.0)
* #throws \Swagger\Client\ApiException on non-2xx response
* #return array of string, HTTP status code, HTTP response headers (array of strings)
*/
public function tasksPostWithHttpInfo($task, $timeframe_begin = null, $timeframe_end = null, $recommendations = null)
{
// verify the required parameter 'task' is set
if ($task === null) {
throw new \InvalidArgumentException('Missing the required parameter $task when calling tasksPost');
}
// parse inputs
$resourcePath = "/tasks";
$httpBody = '';
$queryParams = [];
$headerParams = [];
$formParams = [];
$_header_accept = $this->apiClient->selectHeaderAccept(['application/x-www-form-urlencoded']);
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']);
// header params
if ($timeframe_begin !== null) {
$headerParams['timeframe_begin'] = $this->apiClient->getSerializer()->toHeaderValue($timeframe_begin);
}
// header params
if ($timeframe_end !== null) {
$headerParams['timeframe_end'] = $this->apiClient->getSerializer()->toHeaderValue($timeframe_end);
}
// header params
if ($recommendations !== null) {
$headerParams['recommendations'] = $this->apiClient->getSerializer()->toHeaderValue($recommendations);
}
// default format to json
$resourcePath = str_replace("{format}", "json", $resourcePath);
// body params
$_tempBody = null;
if (isset($task)) {
$_tempBody = $task;
}
// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} elseif (count($formParams) > 0) {
$httpBody = $formParams; // for HTTP post (form)
}
// make the API Call
try {
list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
$resourcePath,
'POST',
$queryParams,
$httpBody,
$headerParams,
'string',
'/tasks'
);
return [$this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader];
} catch (ApiException $e) {
switch ($e->getCode()) {
case 200:
$data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders());
$e->setResponseObject($data);
break;
case 500:
$data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders());
$e->setResponseObject($data);
break;
}
throw $e;
}
}
WHY CODEGEN FAILS ????? please help. is there a way to force the generation of code ?

Related

User Logging automation via Cloudwatch

I Have this task for my company where i have to do a monthly User access review via cloudwatch.
This is a manual process where i have to go to cloudwatch > cloudwatch_logs > log_groups > /var/log/example_access > example-instance and then document the logs for a list of users from random generated date. The example instance is a certificate manager box which is linked to our entire production fleet nodes. I also have to document what command that user used on a specific nodes.
Wondering is there any way i can automate this process and dump it into word docs? it's getting painful as the list of user/employees are increasing. Thanks
Sure there is, I don't reckon you want Word docs though, I'd launch an elasticsearch instance on AWS and then give users who want data Kibana access.
Also circulating word docs in an org is bad juju, depending on your windows/office version it carries risks.
Add this lambda function and then go into cloudwatch and add it as subscription filter to the right log groups.
Note you may get missing log entries if they're not logged in JSON format or have funky formatting, if you're using a standard log format it should work.
/* eslint-disable */
// Eslint disabled as this is adapted AWS code.
const zlib = require('zlib')
const elasticsearch = require('elasticsearch')
/**
* This is an example function to stream CloudWatch logs to ElasticSearch.
* #param event
* #param context
* #param callback
* #param utils
*/
export default (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = true
const payload = new Buffer(event.awslogs.data, 'base64')
const esClient = new elasticsearch.Client({
httpAuth: process.env.esAuth, // your params here
host: process.env.esEndpoint, // your params here.
})
zlib.gunzip(payload, (err, result) => {
if (err) {
return callback(null, err)
}
const logObject = JSON.parse(result.toString('utf8'))
const elasticsearchBulkData = transform(logObject)
const params = { body: [] }
params.body.push(elasticsearchBulkData)
esClient.bulk(params, (err, resp) => {
if (err) {
callback(null, 'success')
return
}
})
callback(null, 'success')
})
}
function transform(payload) {
if (payload.messageType === 'CONTROL_MESSAGE') {
return null
}
let bulkRequestBody = ''
payload.logEvents.forEach((logEvent) => {
const timestamp = new Date(1 * logEvent.timestamp)
// index name format: cwl-YYYY.MM.DD
const indexName = [
`cwl-${process.env.NODE_ENV}-${timestamp.getUTCFullYear()}`, // year
(`0${timestamp.getUTCMonth() + 1}`).slice(-2), // month
(`0${timestamp.getUTCDate()}`).slice(-2), // day
].join('.')
const source = buildSource(logEvent.message, logEvent.extractedFields)
source['#id'] = logEvent.id
source['#timestamp'] = new Date(1 * logEvent.timestamp).toISOString()
source['#message'] = logEvent.message
source['#owner'] = payload.owner
source['#log_group'] = payload.logGroup
source['#log_stream'] = payload.logStream
const action = { index: {} }
action.index._index = indexName
action.index._type = 'lambdaLogs'
action.index._id = logEvent.id
bulkRequestBody += `${[
JSON.stringify(action),
JSON.stringify(source),
].join('\n')}\n`
})
return bulkRequestBody
}
function buildSource(message, extractedFields) {
if (extractedFields) {
const source = {}
for (const key in extractedFields) {
if (extractedFields.hasOwnProperty(key) && extractedFields[key]) {
const value = extractedFields[key]
if (isNumeric(value)) {
source[key] = 1 * value
continue
}
const jsonSubString = extractJson(value)
if (jsonSubString !== null) {
source[`$${key}`] = JSON.parse(jsonSubString)
}
source[key] = value
}
}
return source
}
const jsonSubString = extractJson(message)
if (jsonSubString !== null) {
return JSON.parse(jsonSubString)
}
return {}
}
function extractJson(message) {
const jsonStart = message.indexOf('{')
if (jsonStart < 0) return null
const jsonSubString = message.substring(jsonStart)
return isValidJson(jsonSubString) ? jsonSubString : null
}
function isValidJson(message) {
try {
JSON.parse(message)
} catch (e) { return false }
return true
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
Now you should have your logs going into elastic, go into Kibana and you can search by date and even write endpoints to allow people to query their own data!
Easy way is just give stakeholders Kibana access and let them check it out.
Might not be exactly what ya wanted by I reckon it'll work better.

Webpack 4 Plugin: Add module and get result from loader

I am making a Webpack 4 plugin for fun and to try to understand its internals. The idea is simple:
Parse an HTML template file into a tree;
Get the asset paths from <img src="..."> and <link href="...">;
Add the assets to dependencies to load them through the file-loader;
Get the path emitted from file-loader(which might include a hash)and fix the nodes in the tree;
Emit the final HTML string into a file.
So far, I am stuck at step 4. Parsing the template and extracting the asset paths was easy thanks to parse5, to load the assets, I used the PrefetchPlugin but now I don't know how to get the result from file-loader.
I need to load the result because it generates a hash and might change the location of the asset:
{
exclude: /\.(css|jsx?|mjs)$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]?[sha512:hash:base64:8]`',
},
}],
}
Not only that, but I want to use the url-loader later which might generate the asset encoded. I am trying to get the result from the loader at tapAfterCompile.
The current source code for the plugin is as follows:
import debug from 'debug'
import prettyFormat from 'pretty-format'
import validateOptions from 'schema-utils'
import {dirname, resolve} from 'path'
import {html as beautifyHtml} from 'js-beautify'
import {minify as minifyHtml} from 'html-minifier'
import {parse, serialize} from 'parse5'
import {PrefetchPlugin} from 'webpack'
import {readFileSync} from 'fs'
let log = debug('bb:config:webpack:plugin:html')
const PLUGIN_NAME = 'HTML Plugin'
/**
* This schema is used to validate the plugin’s options, right now, all it does
* is requiring the template property.
*/
const OPTIONS_SCHEMA = {
additionalProperties: false,
type: 'object',
properties: {
minify: {
type: 'boolean',
},
template: {
type: 'string',
},
},
required: ['template'],
}
/**
* Extract an attribute’s value from the node; Returns undefined if the
* attribute is not found.
*/
function getAttributeValue(node, attributeName) {
for (let attribute of node.attrs) {
if (attribute.name === attributeName)
return attribute.value
}
return undefined
}
/**
* Update a node’s attribute value.
*/
function setAttributeValue(node, attributeName, value) {
for (let attribute of node.attrs) {
if (attribute.name === attributeName)
attribute.value = value
}
}
/**
* Recursively walks the parsed tree. It should work in 99.9% of the cases but
* it needs to be replaced with a non recursive version.
*/
function * walk(node) {
yield node
if (!node.childNodes)
return
for (let child of node.childNodes)
yield * walk(child)
}
/**
* Actual Webpack plugin that generates an HTML from a template, add the script
* bundles and and loads any local assets referenced in the code.
*/
export default class SpaHtml {
/**
* Options passed to the plugin.
*/
options = null
/**
* Parsed tree of the template.
*/
tree = null
constructor(options) {
this.options = options
validateOptions(OPTIONS_SCHEMA, this.options, PLUGIN_NAME)
}
/**
* Webpack will call this method to allow the plugin to hook to the
* compiler’s events.
*/
apply(compiler) {
let {hooks} = compiler
hooks.afterCompile.tapAsync(PLUGIN_NAME, this.tapAfterCompile.bind(this))
hooks.beforeRun.tapAsync(PLUGIN_NAME, this.tapBeforeRun.bind(this))
}
/**
* Return the extracted the asset paths from the tree.
*/
* extractAssetPaths() {
log('Extracting asset paths...')
const URL = /^(https?:)?\/\//
const TEMPLATE_DIR = dirname(this.options.template)
for (let node of walk(this.tree)) {
let {tagName} = node
if (!tagName)
continue
let assetPath
switch (tagName) {
case 'link':
assetPath = getAttributeValue(node, 'href')
break
case 'img':
assetPath = getAttributeValue(node, 'src')
break
}
// Ignore empty paths and URLs.
if (!assetPath || URL.test(assetPath))
continue
const RESULT = {
context: TEMPLATE_DIR,
path: assetPath,
}
log(`Asset found: ${prettyFormat(RESULT)}`)
yield RESULT
}
log('Done extracting assets.')
}
/**
* Returns the current tree as a beautified or minified HTML string.
*/
getHtmlString() {
let serialized = serialize(this.tree)
// We pass the serialized HTML through the minifier to remove any
// unnecessary whitespace that could affect the beautifier. When we are
// actually trying to minify, comments will be removed too. Options can be
// found in:
//
// https://github.com/kangax/html-minifier
//
const MINIFIER_OPTIONS = {
caseSensitive: false,
collapseBooleanAttributes: true,
collapseInlineTagWhitespace: true,
collapseWhitespace: true,
conservativeCollapse: false,
decodeEntities: true,
html5: true,
includeAutoGeneratedTags: false,
keepClosingSlash: false,
preserveLineBreaks: false,
preventAttributesEscaping: true,
processConditionalComments: false,
quoteCharacter: '"',
removeAttributeQuotes: true,
removeEmptyAttributes: true,
removeEmptyElements: false,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortAttributes: true,
sortClassName: true,
useShortDoctype: true,
}
let {minify} = this.options
if (minify) {
// Minify.
serialized = minifyHtml(serialized, {
minifyCSS: true,
minifyJS: true,
removeComments: true,
...MINIFIER_OPTIONS,
})
} else {
// Beautify.
serialized = minifyHtml(serialized, MINIFIER_OPTIONS)
serialized = beautifyHtml(serialized, {
indent_char: ' ',
indent_inner_html: true,
indent_size: 2,
sep: '\n',
unformatted: ['code', 'pre'],
})
}
return serialized
}
/**
* Load the template and parse it using Parse5.
*/
parseTemplate() {
log('Loading template...')
const SOURCE = readFileSync(this.options.template, 'utf8')
log('Parsing template...')
this.tree = parse(SOURCE)
log('Done loading and parsing template.')
}
async tapAfterCompile(compilation, done) {
console.log()
console.log()
for (let asset of compilation.modules) {
if (asset.rawRequest == 'assets/logo.svg')
console.log(asset)
}
console.log()
console.log()
// Add the template to the dependencies to trigger a rebuild on change in
// watch mode.
compilation.fileDependencies.add(this.options.template)
// Emit the final HTML.
const FINAL_HTML = this.getHtmlString()
compilation.assets['index.html'] = {
source: () => FINAL_HTML,
size: () => FINAL_HTML.length,
}
done()
}
async tapBeforeRun(compiler, done) {
this.parseTemplate()
// Add assets to the compilation.
for (let {context, path} of this.extractAssetPaths()) {
new PrefetchPlugin(context, path)
.apply(compiler)
}
done()
}
}
Found the answer, after I loaded the dependencies, I can access the generated module's source:
// Index the modules generated in the child compiler by raw request.
let byRawRequest = new Map
for (let asset of compilation.modules)
byRawRequest.set(asset.rawRequest, asset)
// Replace the template requests with the result from modules generated in
// the child compiler.
for (let {node, request} of this._getAssetRequests()) {
if (!byRawRequest.has(request))
continue
const ASSET = byRawRequest.get(request)
const SOURCE = ASSET.originalSource().source()
const NEW_REQUEST = execAssetModule(SOURCE)
setResourceRequest(node, NEW_REQUEST)
log(`Changed: ${prettyFormat({from: request, to: NEW_REQUEST})}`)
}
And execute the module's source with a VM:
function execAssetModule(code, path) {
let script = new Script(code)
let exports = {}
let sandbox = {
__webpack_public_path__: '',
module: {exports},
exports,
}
script.runInNewContext(sandbox)
return sandbox.module.exports
}

TypeError: Argument 3 of SubtleCrypto.wrapKey does not implement interface CryptoKey

I am using Ionic 2 and would like to implement js-jose. It has a jose.min.js file.
Question
Within the Ionic2 structure, how do I import the js-jose library?
UPDATE
This is what I did. It builds with no errors, however, when I run the encrypt function, it does not enter the Promise.
The following is printed:
encryptPerson: Object { id=8, joiningDate=1472815177067, lastAccessDate=1475158964295, more...}
encrypt: password1
But I would also expect it to print the following, but it does not.
encryptPerson: resolve <PersonModel>
There error I get is:
ERROR
TypeError: Argument 3 of SubtleCrypto.wrapKey does not implement interface CryptoKey.
Install
npm install https://github.com/square/js-jose.git --save
code
import * as jose from "jose-jwe-jws";
private cryptographer: any = null;
private rsa_key: any = null;
private encrypter: any = null;
constructor( #Inject(Http) http: Http) {
super();
this.http = http;
this.initEncryption();
}
private encryptPerson(person: PersonModel): Promise<PersonModel> {
console.log('encryptPerson: ', person);
return new Promise<PersonModel>(resolve => {
let password: string = person.password;
this.encrypt(password).then((ciphertext: string) => {
person.password = ciphertext;
console.log('encryptPerson: resolve ', person);
resolve(person);
});
});
}
private encrypt(value: string): Promise<string> {
console.log('encrypt: ', value);
return this.encrypter.encrypt(value);
}
private initEncryption(): void {
this.cryptographer = new jose.Jose.WebCryptographer();
this.rsa_key = {
// n = modulus
"n": "00:c2:4b:af:0f:2d:2b:ad:36:72:a7:91:0f:ee:30:a0:95:d5:3a:46:82:86:96:7e:42:c6:fe:8f:20:97:af:49:f6:48:a3:91:53:ac:2e:e6:ec:9a:9a:e0:0a:fb:1c:db:44:40:5b:8c:fc:d5:1c:cb:b6:9b:60:c0:a8:ac:06:f1:6b:29:5e:2f:7b:09:d9:93:32:da:3f:db:53:9c:2e:ea:3b:41:7f:6b:c9:7b:88:9f:2e:c5:dd:42:1e:7f:8f:04:f6:60:3c:fe:43:6d:32:10:ce:8d:99:cb:76:f7:10:97:05:af:28:1e:39:0f:78:35:50:7b:8e:28:22:a4:7d:11:51:22:d1:0e:ab:6b:6f:96:cb:cf:7d:eb:c6:aa:a2:6a:2e:97:2a:93:af:a5:89:e6:c8:bc:9f:fd:85:2b:0f:b4:c0:e4:ca:b5:a7:9a:01:05:81:93:6b:f5:8d:1c:f7:f3:77:0e:6e:53:34:92:0f:48:21:34:33:44:14:5e:4a:00:41:3a:7d:cb:38:82:c1:65:e0:79:ea:a1:05:84:b2:6e:40:19:77:1a:0e:38:4b:28:1f:34:b5:cb:ac:c5:2f:58:51:d7:ec:a8:08:0e:7c:c0:20:c1:5e:a1:4d:b1:30:17:63:0e:e7:58:8e:7f:6e:9f:a4:77:8b:1e:a2:d2:2e:1b:e9",
// e = publicExponent
"e": 65537,
// d = privateExponent
"d": "37:b6:4b:f4:26:17:a8:0b:3c:c5:1f:ab:59:b9:47:d2:ae:d9:8e:ee:4e:79:48:ab:0d:34:61:06:0f:78:8b:d4:ba:ef:6b:f4:7a:22:d8:c4:6f:70:89:5d:9c:b3:a1:8b:e8:88:57:dd:07:9e:c2:2b:12:52:a3:eb:b9:a8:24:01:7e:53:2b:7a:34:50:d7:0c:75:d8:69:a3:87:dd:4b:fc:c1:c3:2f:bd:0e:57:16:8d:ea:de:8e:de:ff:e4:9a:9f:aa:e8:d2:5f:b3:27:ef:f9:ca:50:97:2e:fd:99:1c:34:dd:0c:bb:dd:d0:b9:bf:4f:dc:9d:de:94:50:66:2c:58:7e:c2:31:8b:41:56:49:6a:e6:11:14:53:a1:45:0d:15:8b:26:79:0f:c9:dc:ac:dc:c7:bc:55:2c:96:ed:a7:29:09:04:ee:00:74:60:e1:bc:97:7b:0a:b6:f2:83:82:79:65:e0:aa:88:9f:90:b0:0d:76:4d:3c:08:7e:a5:05:19:d4:8b:54:d3:f1:c1:a3:e3:a5:1e:aa:d6:c4:94:ad:6c:b3:8f:85:06:8a:6f:52:f8:a3:c3:e0:8d:67:35:2f:d4:18:fc:70:f4:71:bf:18:88:d6:a7:b7:04:8e:d3:06:ca:83:c3:2d:21:98:65:c9:41:2c:77:bf:4c:7c:8c:2c:01",
// p = prime1
"p": "00:fa:d6:06:46:5c:04:70:e6:ec:47:02:96:02:a5:e2:41:9d:bd:7b:97:28:a4:c5:3b:b5:9b:0a:6b:7d:b6:44:8a:28:1e:d1:ef:cb:44:ef:eb:4d:08:74:80:f5:cf:3b:b7:40:10:60:c9:18:1e:a5:76:4b:41:37:06:b2:71:03:60:25:77:db:d0:b2:21:dc:b0:32:90:a2:10:9a:d5:e6:e3:11:42:a1:9a:7a:26:3c:d3:12:56:db:25:07:69:be:ae:2c:b9:33:6c:29:e3:65:b9:5b:05:84:05:e6:da:c4:f4:3f:ab:84:60:6e:f0:5f:ba:a8:98:8f:72:2c:c8:40:d1",
// q = prime2
"q": "00:c6:4b:ac:fe:40:1c:dc:6c:78:07:cc:3e:db:4e:d5:d0:17:3b:8f:04:f0:ae:c4:22:0d:8b:0a:4d:0f:9e:fe:c7:e6:38:b5:53:ba:a9:e8:f0:47:28:14:25:95:6a:79:ab:db:86:97:82:c5:1e:bd:80:a5:aa:a2:b7:a5:c7:48:17:c4:d9:c7:4f:50:2a:69:67:15:4c:0b:f5:e6:fb:20:23:5d:ea:ae:6c:c6:74:ba:cc:f8:06:2b:41:1f:b6:3f:2a:93:fa:f9:e1:ee:93:c3:92:ad:49:c7:8f:db:72:ff:6b:f0:f0:d6:2f:83:ce:1c:82:16:89:57:01:9f:49:2f:99",
// dp = exponent1
"dp": "57:d4:c1:75:b9:9a:c4:7d:d7:96:35:cd:99:37:c4:b5:fd:29:f0:30:c9:c6:88:59:94:09:a9:e8:61:a8:84:ef:6b:84:ff:35:dc:13:53:7f:2d:06:1c:e5:5b:2d:29:57:cd:52:ee:d0:fb:65:1f:c3:00:2e:e1:b9:b2:99:e7:f8:ae:a5:fd:8e:62:11:81:59:21:1b:8b:e4:0c:93:81:b9:58:bd:e0:20:5b:4d:30:57:28:40:c9:93:79:b9:09:4f:ab:d1:5d:b4:2e:26:b5:e3:e5:7f:54:ef:4c:1a:a6:84:70:16:fa:cf:59:89:49:bb:ee:75:1d:25:79:90:d5:41",
// dq = exponent2
"dq": "00:ab:eb:a8:8c:b7:21:4e:aa:6c:56:b6:6a:38:d1:dc:e6:91:7d:fd:bd:96:be:af:25:a7:00:49:6a:0e:85:16:f8:51:4e:11:48:0a:aa:8d:5e:e5:12:86:85:1f:4a:35:3b:1f:15:4d:fe:fe:d0:6c:14:41:8d:f3:8d:ad:99:5d:93:de:03:c2:9d:ad:2f:58:3b:1b:67:d7:66:d7:60:1a:b9:0f:10:0d:32:19:cd:d2:b7:2a:c2:8e:75:e3:fc:aa:3f:4c:15:68:d8:cd:74:27:37:e0:2d:fb:6b:6a:24:05:f7:9b:e9:f2:89:37:89:57:86:21:eb:e9:17:6a:f6:94:e1",
// qi = coefficient
"qi": "0a:ed:5f:30:67:d5:e5:6e:4a:7a:35:49:fe:16:2f:1e:91:2b:39:c3:01:d3:d4:c0:4d:b3:fc:08:b0:66:e9:44:10:9e:5b:5a:ea:83:a5:9c:95:7a:58:70:35:28:e5:4d:ba:19:de:0d:66:f9:db:5c:f6:5b:24:27:9d:0b:2d:44:40:eb:33:3a:19:e2:1d:c0:b0:16:99:d1:c1:52:84:02:d6:67:06:32:f8:4d:cb:42:9f:7c:8a:e0:ad:df:40:6f:e4:8c:f6:f6:9e:1d:bd:43:e3:38:91:a2:d0:9e:60:ff:9d:8c:fb:72:5b:df:95:30:17:d2:f2:cb:7d:92:56:0a"
};
this.encrypter = new jose.JoseJWE.Encrypter(this.cryptographer, this.rsa_key);
}
Did you try running the following:
npm install node-jose
UPDATE:
You can add a catch block and get the error message in a case of a failure - you can find an example for the catch block here: github.com/square/js-jose

Could not resolve module 'fs' webpack

I am trying to unit test my code. I need to test an api call that has a relative url. Am trying to use supertest for api mocks.
Here's a snippet of my test code:
const express = require('express');
const app = express();
const supertest = require('supertest');
app.use(express.bodyParser());
it('should get required details', (done) => {
supertest(app)
.get('/home/api/getdetails')
.expect(200, { response: { foo: 'bar', done);
const expectedActions = [{ type: 'DETAILS',
payload: { foo: 'bar' } }];
const store = mockStore({}, expectedActions);
const func = getDetails();
// eslint-disable-next-line
console.log("func"+func);
const dispatch = sinon.spy();
func(dispatch);
expect(store.getActions()).
to.deep.equal(expectedActions);
});
Here's my webpack.config.js
var path = require('path');
var env = require('./env');
// List of allowed environments
var allowedEnvs = ['env1', 'env2', 'env3', 'env4', 'env5', 'env6', 'env7', 'env7'];
// Get available configurations
var configs = {
env0: require(path.join(__dirname, 'cfg/env0')),
env1: require(path.join(__dirname, 'cfg/env1')),
env2: require(path.join(__dirname, 'cfg/env2')),
env3: require(path.join(__dirname, 'cfg/env3')),
env4: require(path.join(__dirname, 'cfg/env4')),
env5: require(path.join(__dirname, 'cfg/env5')),
env6: require(path.join(__dirname, 'cfg/env6')),
env7: require(path.join(__dirname, 'cfg/env7')),
env8: require(path.join(__dirname, 'cfg/env8')),
};
/**
* Get an allowed environment
* #param {String} env
* #return {String}
*/
function getValidEnv(env) {
var isValid = env && env.length > 0 && allowedEnvs.indexOf(env) !== -1;
return isValid ? env : 'dev';
}
/**
* Build the webpack configuration
* #param {String} env Environment to use
* #return {Object} Webpack config
*/
function buildConfig(env) {
var usedEnv = getValidEnv(env);
return configs[usedEnv];
}
module.exports = buildConfig(env);
Everywhere, it is said that just by adding,
node:{
fs: 'empty',
}
would solve the issue. But, the issue is not resolved for me.
Could anyone please help me with this?
Thank you,
Aswini J

IE9: store.find is failing

I can't seem to fetch new data in Internet Explorer 9. For the purpose of an example I test the store this way:
App.__container__.lookup('store:main').find('style')
The only error I receive is the following:
SCRIPT5022: Error: Assertion Failed: [object Object]
Does Ember-data works out of the box (without polyfills, ...) in Internet Explorer 9?
versions:
Ember: 1.9.1
Ember-data: 1.0.0-beta.12
Problem solved. When doing an AJAX request with jQuery, this normally happens through the XMLHttpRequest object.
On IE8-9, this object is not present, instead it uses XDomainRequest. The simplest fix for this is adding: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest.
ember-data works out of the box with IE8+. According to this issue:
We've been supporting IE8 with our platform (built on Ember) for a
while now. Things I know:
shim/sham is not needed, it's polyfilled by Ember and Ember-Data.
You will need it if you want additional things like .bind() on a function, then you must prepend it to the vendor file (using Brocfile)
and we only include the shim for that purpose, not the sham
Solution Synthesis
Reason :
On IE8-9, this object is not present, instead it uses XDomainRequest.
Solution :
The issue is solved. When using an AJAX request with jQuery. Normally this is done through the XMLHttpRequest object. A simple fix would be using the Open-Source jQuery-ajaxTransport-XDomainRequest
Code : Adding :
jQuery-ajaxTransport-XDomainRequest.js
/*!
* jQuery-ajaxTransport-XDomainRequest - v1.0.4 - 2015-03-05
* https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
* Copyright (c) 2015 Jason Moon (#JSONMOON)
* Licensed MIT (/blob/master/LICENSE.txt)
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals.
factory(jQuery);
}
}(function($) {
// Only continue if we're on IE8/IE9 with jQuery 1.5+ (contains the ajaxTransport function)
if ($.support.cors || !$.ajaxTransport || !window.XDomainRequest) {
return $;
}
var httpRegEx = /^(https?:)?\/\//i;
var getOrPostRegEx = /^get|post$/i;
var sameSchemeRegEx = new RegExp('^(\/\/|' + location.protocol + ')', 'i');
// ajaxTransport exists in jQuery 1.5+
$.ajaxTransport('* text html xml json', function(options, userOptions, jqXHR) {
// Only continue if the request is: asynchronous, uses GET or POST method, has HTTP or HTTPS protocol, and has the same scheme as the calling page
if (!options.crossDomain || !options.async || !getOrPostRegEx.test(options.type) || !httpRegEx.test(options.url) || !sameSchemeRegEx.test(options.url)) {
return;
}
var xdr = null;
return {
send: function(headers, complete) {
var postData = '';
var userType = (userOptions.dataType || '').toLowerCase();
xdr = new XDomainRequest();
if (/^\d+$/.test(userOptions.timeout)) {
xdr.timeout = userOptions.timeout;
}
xdr.ontimeout = function() {
complete(500, 'timeout');
};
xdr.onload = function() {
var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
var status = {
code: 200,
message: 'success'
};
var responses = {
text: xdr.responseText
};
try {
if (userType === 'html' || /text\/html/i.test(xdr.contentType)) {
responses.html = xdr.responseText;
} else if (userType === 'json' || (userType !== 'text' && /\/json/i.test(xdr.contentType))) {
try {
responses.json = $.parseJSON(xdr.responseText);
} catch(e) {
status.code = 500;
status.message = 'parseerror';
//throw 'Invalid JSON: ' + xdr.responseText;
}
} else if (userType === 'xml' || (userType !== 'text' && /\/xml/i.test(xdr.contentType))) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = false;
try {
doc.loadXML(xdr.responseText);
} catch(e) {
doc = undefined;
}
if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
status.code = 500;
status.message = 'parseerror';
throw 'Invalid XML: ' + xdr.responseText;
}
responses.xml = doc;
}
} catch(parseMessage) {
throw parseMessage;
} finally {
complete(status.code, status.message, responses, allResponseHeaders);
}
};
// set an empty handler for 'onprogress' so requests don't get aborted
xdr.onprogress = function(){};
xdr.onerror = function() {
complete(500, 'error', {
text: xdr.responseText
});
};
if (userOptions.data) {
postData = ($.type(userOptions.data) === 'string') ? userOptions.data : $.param(userOptions.data);
}
xdr.open(options.type, options.url);
xdr.send(postData);
},
abort: function() {
if (xdr) {
xdr.abort();
}
}
};
});
return $;
}));