function looks like this:
I am using first time nestjs for generators, it seems like i have some issue in collection.json
export function application(options: any) {
// eslint-disable-next-line #typescript-eslint/no-unused-vars
return (_tree: Tree, _context: SchematicContext) => {
return chain([
externalSchematic('#nestjs/schematics', 'application', options),
generate(options),
]);
};
}
export function generate(_options: any): Rule {
return (tree: Tree, context: SchematicContext) => {
return chain([
addDependencies(tree, _options),
renderTemplates(_options),
modifyGeneratedFiles(_options),
])(tree, context);
};
}
collection.json file looks like this.
"schematics": {
"resolver": {
"description": "Nodejs GraphQL project scaffold",
"factory": "./resolver-generator/index#application",
"schema": "./resolver-generator/resolver-schema.json"
},
"rest": {
"description": "Nodejs Rest generator project scaffold",
"factory": "./rest-generator/index#applicationRest",
"schema": "./rest-generator/rest-schema.json"
}
Thank you for help i am able to solve it, it was happening bcoz of wrong function name when we use nestjs/schematics we have to pass application not applictionRest
Related
I have installed a node module called #SomeOrg/SomeLibrary. It is being imported in source code in multiple ways in multiple files. For example,
import { SOME_IMPORTS_FROM_MODULE1} from "#SomeOrg/SomeLibrary/Module1"
import {SOME_IMPORTS_FROM_SUB_MODULE} from "#SomeOrg/SomeLibrary/Module1/SubModule"
import {SOME_IMPORTS_FROM_MODULE2} from "#SomeOrg/SomeLibrary/Module2"
etc.
How can I mock the #SomeOrg/SomeLibrary using JEST so that it would work correctly on each file's test cases? Actually, I have tried the following way to mock it in a file and added it to the setupFiles key in the JEST config.
jest.mock("#SomeOrg/SomeLibrary", () => ({
Module1: {
SOME_IMPORTS_FROM_MODULE1: jest.fn(),
SubModule: {
SOME_IMPORTS_FROM_SUB_MODULE: jest.fn()
}
},
Module2: {
SOME_IMPORTS_FROM_MODULE2: jest.fn()
}
))
But it is not working. Please suggest me a generic way so that it would work for all relative paths imported from a node module.
Here is the working solution for the above scenario. But this is not an optimal one. Edits are welcome.
1. module1_mock.js
jest.mock('#SomeOrg/SomeLibrary/Module1', () => {
return {
SOME_IMPORTS_FROM_MODULE1: jest.fn()
}
})
2. sub_module_mock.js
jest.mock('#SomeOrg/SomeLibrary/Module1/SubModule', () => {
return {
SOME_IMPORTS_FROM_SUB_MODULE: jest.fn()
}
})
3. module2_mock.js
jest.mock('#SomeOrg/SomeLibrary/Module2', () => {
return {
SOME_IMPORTS_FROM_MODULE2: jest.fn()
}
})
4. module_mock.js
jest.mock('#SomeOrg/SomeLibrary', () => {
return {
__esModule: true,
default: jest.fn(),
}
})
Once the above files are created, add them to the setupFiles key inside the jest configuration file like below.
{
...defaultConfig,
setupFiles: ["DIRECTORY_OF_MOCKS/module1_mock.js","DIRECTORY_OF_MOCKS/sub_module_mock.js","DIRECTORY_OF_MOCKS/module2_mock.js","DIRECTORY_OF_MOCKS/module_mock.js"]
}
I'm using Shopify's rest client for node and its request and response look something like this:
request
client.get({
path: 'orders/count.json',
query: { fulfillment_status: 'unfulfilled' }
})
If there's an error:
{
"errors": "[API] Invalid API key or access...",
"code": 2342,
"statusText": "Authentication Error",
"Headers": "..."
}
If there's no error:
{
"body": { "count": 8 },
"code": 2342,
"statusText": "Authentication Error",
"Headers": "..."
}
I'd like to add some boilerplate over this client library so that I can get the typings of the response. This is what I'm trying to do but it's not working too well:
const customClient = {
get: async <T, K extends string>(params: GetRequestParams) => {
const response = (await client.get(params));
if (response.body.errors) return { errors: response.body.errors };
// somehow index it. obviously not with the type declaration???
return { [K]: response.body[K] as T };
},
}
With the hopes that I can use it as.
const { count, error } = customClient.get<number, "count">({ ... });
Any help would be appreciated. I have an entire file of the Shopify API types that I would like to leverage. A solution to this would be perfect!
A possible implementation can look like this:
const customClient = {
get: async <T, K extends string>(params: GetRequestParams):
Promise<Partial<Record<K, T> & { errors: string }>> =>
{
const response = (await client.get(params));
if (response.body.errors) return { errors: response.body.errors } as any;
return {
[Object.keys(response)[0]]: response[Object.keys(response)[0]]
} as any
},
}
As you correctly noted, we can't use the TypeScript generic types when constructing the returning object. We need to use JavaScript features instead. In this case I just took the first key of the response and used it for the key of the returning object as well as to index the response object.
The return type of the function is a Promise consisting of both a Record with K and T as keys and values and the error type. I used Partial here since they are not both required.
Destructing the response leads to the correct types now:
async function main(){
const { count, errors } = await customClient.get<number, "count">({} as any);
// count: number | undefined
// errors: string | undefined
}
Playground
Have a simply issue. Currently doing some pet-project and took nodejs api for it.
The API is written on nodejs and want to implements with my react-app.
But bumped into i can not create dummy date and to try testing the ui.
Here is method of creating:
.post('/', function (req, res) {
var directory = _.pick(req.body, [
'parentId',
'name'
]
)
, parent = _.find(store.directories, function (dir) {
return dir.id == directory.parentId
})
if (parent) {
_.assign(directory, { id: idGenerator.getNext() })
store.directories.push(directory)
res.send(directory)
} else {
res.status(500).send('no parent')
}
})
The problem is i can not even to make a new row in postman:
{
"parentId": 1,
"name": "some title"
}
Sending RAW => json and receiving: "Cannot POST /"
(Edited to incorporate comments)
So I apologize in advance for the long question. I don't know how else to ask it.
I'm trying to finish up a full-stack web app using React, Node, and DynamoDB. POST and GET requests are working fine, but I'm stuck on PUT. My mock PUT request works fine, but once I try it from the front end in React, I get the error mentioned in the title. I'll show the back end code first, then the mock update, and then the front end.
import handler from "./libs/handler-lib";
import dynamoDb from "./libs/dynamodb-lib";
export const main = handler(async (event, context) => {
const data = JSON.parse(event.body);
const params = {
TableName: process.env.tableName,
Key: {
userId: event.requestContext.identity.cognitoIdentityId,
activityId: event.pathParameters.activityId
},
UpdateExpression: "SET title = :title, activityType = :activityType, activityRoutine = :activityRoutine, activityComment = :activityComment",
ExpressionAttributeValues: {
":title": data.title || null,
":activityType": data.activityType || null,
// ":activityRoutine": data.activityRoutine == '' ? "None" : data.activityRoutine,
// ":activityComment": data.activityComment == '' ? "None" : data.activityComment
":activityRoutine": data.activityRoutine || null,
":activityComment": data.activityComment || null
},
ReturnValues: "ALL_NEW"
};
await dynamoDb.update(params);
return { status: true };
This mock update event works without issue:
{
"body": "{\"title\":\"test\",\"activityType\":\"testing\",\"activityRoutine\":\"\",\"activityComment\":\"\"}",
"pathParameters": {
"activityId": "long-alphanumeric-id"
},
"requestContext": {
"identity": {
"cognitoIdentityId": "us-east-and-so-on"
}
}
}
But this code, which produces the exact same Javascript object as the mock, is not okay with AWS:
function saveActivity(activity) {
try {
return API.put("activities", `/activities/${id}`, {
body: activity
});
} catch(e) {
console.log("saveActivity error:", e);
}
}
async function handleSubmit(event) {
event.preventDefault();
setIsLoading(true)
try {
await saveActivity({
title: title, activityType: activityType, activityRoutine: activityRoutine, activityComment: activityComment
// "key": {userId: userId, activityId: activityId}
// "pathParameters": {"id": activityId},
// "requestContext": {"identity": {"cognitoIdentityId": userId}}
});
} catch(e) {
console.log(e)
setIsLoading(false)
}
}
If anyone needs to see more of the code, I'm happy to share, but I figured this question is already getting very long. Any code you see commented out has been tried before without success.
I'd also be happy if someone could point me in the right direction as far as the AWS documentation is concerned. I've been going off of a tutorial and modifying it where need be.
Any help is appreciated!
I have a helper which I use for Detox tests which hold abstractions of most commonly occurring actions. Like this.
/**
* Looks for a search input and inputs the query
*/
export const inputSearchQuery = async ({ query = '', placeholderText = '' }) => {
if (placeholderText) {
// look for search input
await expect(element(by.id(TestID.SEARCH_INPUT).withDescendant(by.text(placeholderText)))).toBeVisible();
// tap search input
await element(by.id(TestID.SEARCH_INPUT).withDescendant(by.text(placeholderText))).tap();
// type in query
await element(by.id(TestID.SEARCH_INPUT).withDescendant(by.text(placeholderText))).typeText(query);
} else {
// look for search input
await expect(element(by.id(TestID.SEARCH_INPUT))).toBeVisible();
// tap search input
await element(by.id(TestID.SEARCH_INPUT)).tap();
// type in query
await element(by.id(TestID.SEARCH_INPUT)).typeText(query);
}
};
I want this layer of abstraction to be tested with Jest. So I did the following,
describe('e2e helper', () => {
describe('inputSearchQuery()', () => {
test('should check whether the search input is visible', async () => {
const mockToBeVisible = jest.fn();
await inputSearchQuery({});
expect(mockToBeVisible).toBeCalledTimes(1);
});
});
});
And obviously got the error,
ReferenceError: element is not defined
I understand that element comes from the environment. How do I configure my Jest setup...
"jest": {
"preset": "react-native",
"snapshotSerializers": [
"./node_modules/enzyme-to-json/serializer"
],
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-navigation)"
],
"moduleNameMapper": {
"package.json": "<rootDir>/__mocks__/package.json"
},
"testPathIgnorePatterns": [
"/e2e/"
],
// I'm guessing something like this but doesn't work out of the box
"testEnvironment": "detox"
},
...to address this?